69. Sqrt(x)

 

Promble

Given a non-negative integer x, return the square root of x rounded down to the nearest integer. The returned integer should be non-negative as well.

You must not use any built-in exponent function or operator.

For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python.

Input: x = 4
Output: 2
Explanation: The square root of 4 is 2, so we return 2.
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we round it down to the nearest integer, 2 is returned.

Constraints:

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

Approach

  1. if x is 0, return 0
  2. initialize first to 1 and last to x
  3. while first is less than or equal to last, do the following:
    1. compute mid = first + (last - first)//2
    2. if mid * mid = x, return mid
    3. if mid * mid > x, update last = mid - 1
    4. if mid * mid < x, update first = mid + 1

Code

class Solution:
    def mySqrt(self, x: int) -> int:
        if x == 0:
            return 0
        first, last = 1, x
        while first <= last:
            mid = first + (last-first) // 2
            if mid == x // mid:
                return mid 
            elif mid > x//mid:
                last = mid - 1
            else:
                first = mid + 1 
        return last