69. Sqrt(x)

1. Description

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.

2. Example

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.

3. Constraints

  • 0 <= x <= $2^{31} - 1$

4. Solutions

Time complexity: O($log_x$)
Space complexity: O(1)

class Solution {
public:
    int mySqrt(const int x) {
        int square_root = 0;
        for (long left = 0, right = x; left <= right; ) {
            long middle = (left + right) / 2;
            if (middle * middle <= x) {
                square_root = middle;
                left = middle + 1;
            } else {
                right = middle - 1;
            }
        }

        return square_root;
    }
};
comments powered by Disqus