x的平方根(二分查找实现)

x的平方根(二分查找实现)

class Solution {
    
    
    public int mySqrt(int x) {
    
    
        int l = 0, r = x, ans = -1;
        while (l <= r) {
    
    
            int mid = (l + r)/ 2;
            if ((long) mid * mid <= x) {
    
    
                ans = mid;
                l = mid + 1;
            } else {
    
    
                r = mid - 1;
            }
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/xiaomagezuishuai/article/details/114199095