LeetCode 69. Sqrt(x)

Post by ailswan Aug. 09, 2024

69. Sqrt(x)

Problem Statement

link: LeetCode.cn LeetCode 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.

Example:

Input: x = 4 Output: 2

Input: x = 8 Output: 2

Constraints: 0 <= x <= 231 - 1

Solution Approach

Use binary search to find the square root by narrowing the range of possible values until the closest integer is found.

Algorithm

  1. Set Search Range: Start with left at 0 and right at x to cover all possible square root values.
  2. Binary Search: Repeatedly check the midpoint. If its square is too high, move the right boundary; if too low, move the left boundary and save the midpoint as a potential answer.
  3. Return Closest: Once the search range is exhausted, return the last midpoint that didn’t exceed x.

Implement

    class Solution:
    def mySqrt(self, x: int) -> int:
        l, r = 0, x
        res = 0
        while l <= r:
            m = l + ((r - l) // 2)
            if m ** 2 > x:
                r = m - 1
            elif m ** 2 < x:
                l = m + 1
                res = m
            else:
                return m 
        return res