实现int sqrt(int x)。
计算并返回x的平方根。
Implement int sqrt(int x).
Compute and return the square root of x.
首先给大家推荐维基百科:
en.wikipedia.org/wiki/Binary_search_tree
大家也可以看看类似的一道题:
LeetCode 50 Pow(x, n)(Math、Binary Search)(*)
然后我就直接贴代码了……
class Solution {
public:
int mySqrtHelper(int x, int left, int right) {
if (x == 0) return 0;
if (x == 1) return 1;
int mid = left + (right - left) / 2;
if (mid > x / mid) right = mid;
if (mid <= x / mid)left = mid;
if (right - left <= 1) return left;
else mySqrtHelper(x, left, right);
}
int mySqrt(int x) {
return mySqrtHelper(x, 0, x);
}
};
LeetCode 69 Sqrt(x)(Math、Binary Search)(*)
原文:http://blog.csdn.net/nomasp/article/details/50811232