69. Sqrt(x)

Problem


Tags: Math, Binary Search

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

Example 1:

Input: x = 4
Output: 2

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

Constraints:

  • 0 <= x <= 2^31 - 1

Code

C

// 69. Sqrt(x) (3/11/53959)
// Runtime: 4 ms (58.05%) Memory: 5.47 MB (80.99%) 

int mySqrt(int64_t x) {
    // 左界為 l,右界為 r
    int64_t l = 0, r = x;
    
    // 二分搜尋,直到 l 超過 r
    while(l <= r) {
        // 取中間值
        int64_t m = l + (r - l) / 2;
        
        // 如果測試值比 x 小則往上找,反之往下找
        if (m * m <= x) {
            l = m + 1;
        } else {
            r = m - 1;
        }
    }
    
    return r;
}