LeetCode 69. Sqrt(x)(整数二分)

题目链接:点击这里

在这里插入图片描述 S q r t ( x ) Sqrt(x) ,转换为求 a n s ans 使得 x = a n s 2 x=ans^2

x x a n s ans 单调、正相关,所以,考虑在 [ 0 , x ] [0, x] 范围内二分找到一个 a n s ans 使得 a n s 2 = x ans^2=x

数据会爆掉int

class Solution {
public:
    //当前的mid小于等于时返回true,当前的mid大于时返回false
    int check(long long mid, long long x) {
        return mid*mid <= x;
    }

    int mySqrt(int x) {
        long long L = 0, R = x, mid, ans;   //[L,R]
        while(L<=R)
        {
            long long mid = L+(R-L)/2;
            if(check(mid,x))
            {
                ans = mid;
                L = mid + 1;
            }
            else
                R = mid - 1;
        }
        return ans;
    }
};
发布了690 篇原创文章 · 获赞 103 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_42815188/article/details/104065021