Leetcode: Sqrt(x)

来源:互联网 发布:闲鱼淘宝介入提交凭证 编辑:程序博客网 时间:2024/06/06 12:44

Question

Implement int sqrt(int x).

Compute and return the square root of x.

Show Tags
Show Similar Problems


Solution

Analysis

Get idea from Code Ganker.

Code

class Solution(object):    def mySqrt(self, x):        """        :type x: int        :rtype: int        """        if x<0:            return None        if x==0:            return 0        l,r = 1, x/2+1        while l<=r:            m = (l+r)/2            if x>=m**2 and x<(m+1)**2:                return m            if x<m**2:                r = m-1            else:                l = m+1        return 0
0 0
原创粉丝点击