首页 > 其他分享 >Sqrt(x)

Sqrt(x)

时间:2023-06-19 10:23:42浏览次数:37  
标签:use 0.5 negative Sqrt non integer

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

标签:use,0.5,negative,Sqrt,non,integer
From: https://www.cnblogs.com/artwalker/p/17490452.html

相关文章