代码改变世界

[LeetCode] 69. Sqrt(x)_Easy tag: Binary Search

2018-08-31 06:35  Johnson_强生仔仔  阅读(195)  评论(0编辑  收藏  举报

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

04/15/2019 UPdate: 利用binary search,找last index that i * i <= x.

Time: O(lg n) , Space: O(1)

Code
class Solution:
    def sqrt(self, x):
        if x < 2: return x
        l, r = 1, x  # r * r > x for sure
        while l + 1 < r:
            mid = l + (r - l)//2
            value = mid * mid
            if value > x:
                r = mid
            elif value < x:
                l = mid
            else:
                return mid
        return l

 



class Solution:
    def sqrt(self, num):
        ans = num
        while ans*ans > num:
            ans = (ans + num//ans)//2
        return ans