Sqrt(x)
Implementint sqrt(int x)
.
Compute and return the square root of x.
注意:Submission Result:Time Limit Exceeded。因为mid * mid will overflow when mid>sqrt(INT_MAX)
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
l, r = 0, x
while l <= r:
mid = (r+l)/2
if mid*mid <= x < (mid+1)*(mid+1):
return mid
elif mid*mid > x:
r = mid - 1
else:
l = mid + 1
二刷:
九章模版
注意循环结束后判断条件,例如sqrt(8)=2
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
start, end = 1, x
while start+1 < end:
mid = (start+end)/2
if mid*mid < x:
start = mid
else:
end = mid
if end * end <= x:
return end
return start
Last updated
Was this helpful?