LeetCode: Sqrt(x)

思路:二分查找,但是注意到一个INT数的平方会超过INT的表示范围,所以,中间过程需要用long long 类型保存。

code:

class Solution {
public:
    int sqrt(int x) {
        long long left = 0, right = x;
        while(left <= right){
            long long mid = (left + right) / 2;
            if(mid*mid == x)return mid;
            else if(mid * mid < x)
                left = mid+1;
            else
                right = mid-1;
        }
        return right;
    }
};


你可能感兴趣的:(LeetCode: Sqrt(x))