[Leetcode] 69. Sqrt(x)

版权声明:转载请联系博主 https://blog.csdn.net/zxtalentwolf/article/details/84347963

 这个题的问题在于二分搜索后的结果的平方一定要小于目标值,所以特殊情况下要减一

class Solution {
public:
    int mySqrt(int x) {
        int l = 0;
        int r = x;
        long mid = l + ((r - l) >> 1);
        while(l <= r){
            mid = l + ((r - l) >> 1);
            long res = mid * mid;
            if(res < x){
                l = mid + 1;
            }else if(res > x){
                r = mid - 1;
                if(l > r){
                    mid = r;
                }
            }else{
                break;
            }
        }
        return mid;
        
    }
};

猜你喜欢

转载自blog.csdn.net/zxtalentwolf/article/details/84347963