Leetcode:Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
分析:二分查找。首先确定二分查找终止的条件和返回条件,其次对于与数字有关的题要注意int的表示范围防止溢出(比如该题两个int相乘可能会超过int的范围,故采用x/mid与mid比较大小)。代码如下:
class Solution { public: int sqrt(int x) { if(x == 0) return 0; if(x == 1 || x == 2 || x == 3) return 1; int l = 1, r = x/2; while(l <= r){ int mid = (l + r)/2; if(x/mid == mid || x/mid > mid && x/(mid+1) < (mid+1)) return mid; if(x/mid < mid) r = mid-1; else if(x/mid > mid) l = mid + 1; } } };