Sqrt(x)

发布时间 2023-06-19 10:21:48作者: Artwalker

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.
Solution:

class Solution(object):
    def mySqrt(self, x):
        l, r, ans = 0, x, -1
        while l <= r:
            mid = (l + r) // 2
            if mid ** 2 <= x:
                ans = mid
                l = mid + 1
            else:
                r = mid - 1
        return ans