LeetCode【69. The square root of x】

Given a non-negative integer  x , calculate and return  x the  arithmetic square root  .

Since the return type is an integer, only  the integer part  of the result is retained , and the decimal part will be  rounded off.

NOTE: Any built-in exponential functions and operators such as  pow(x, 0.5) or  are not allowed x ** 0.5 .

Example 1:

Input: x = 4
 Output: 2

Example 2:

Input: x = 8
 Output: 2
 Explanation: The arithmetic square root of 8 is 2.82842..., since the return type is an integer, the decimal part will be rounded off.

hint:

  • 0 <= x <= 231 - 1

public int mySqrt(int x) {
    if (x == 0) {
        return 0;
    }
    
    int left = 1;
    int right = x;
    int result = 0;
    
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (mid <= x / mid) {
            left = mid + 1;
            result = mid;
        } else {
            right = mid - 1;
        }
    }
    
    return result;
}

Guess you like

Origin blog.csdn.net/s_sos0/article/details/133191137