版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/50811232
翻译
实现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);
}
};