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
Last updated
Was this helpful?