[LeetCode-Java Exercise] The square root of 69.x (simple)

1. Title description

Insert picture description here

2. Problem solving ideas

Binary search:
Since the integer part ans of the square root of x is the maximum k value that satisfies k^2 ≤x, we can perform a binary search on k to get the answer.
The lower bound of binary search is 0, and the upper bound can be roughly set to x. In each step of the binary search, we only need to compare the size relationship between the square of the middle element mid and x, and adjust the range of the upper and lower bounds through the result of the comparison. Since all our operations are integer operations, there will be no errors, so after getting the final answer ans, there is no need to try ans+1 again.

3. Code implementation

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

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/114005305