您的位置:首页 > 编程语言

leetcode-Sqrt(x) (2014.4.7)

2014-04-13 22:06 225 查看
Implement int sqrt(int x).
Compute and return the square root of x.

注意二分搜索的写法。
class Solution {
public:
    int sqrt(int x) {
        long long low=0;
        long long high=x/2+1;
        long long middle;
        while(low<=high){
            middle=(high+low)/2;
            long long p=middle*middle;
            if(p<x){
                low=middle+1;
            }else if(p>x){
                high=middle-1;
            }else{
                return middle;
            }
        }
        return high;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 编程