本文主要是介绍Leetcode: Sqrt(x),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Implement int sqrt(int x).
Compute and return the square root of x.
依然二分法….这道题虽然简单,但是有一些细节需要注意,我是提交了好几遍才通过的!
参考代码:
class Solution
{
public:int mySqrt(int x) {if (x < 2) return x;int left = 1;int right = x / 2;int result;while (left <= right){int middle = (left + right) / 2;if (x / middle < middle)right = middle - 1;else if (x / middle > middle){left = middle + 1;result = middle;}else return middle;}return result;}
};
这篇关于Leetcode: Sqrt(x)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!