您的位置:首页 > 其它

LeetCode 69 Sqrt(x)(Math、Binary Search)(*)

2016-03-05 22:50 411 查看

翻译

[code]实现int sqrt(int x)。

计算并返回x的平方根。


原文

[code]Implement int sqrt(int x).

Compute and return the square root of x.


分析

首先给大家推荐维基百科:

zh.wikipedia.org/wiki/二元搜尋樹

en.wikipedia.org/wiki/Binary_search_tree

大家也可以看看类似的一道题:

LeetCode 50 Pow(x, n)(Math、Binary Search)(*)

然后我就直接贴代码了……

代码

[code]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);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: