class Solution:
"""
@param: x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# 二分法 505ms
i, j = 0, x/2 + 1
while i <= j:
mid = i + (j - i)/2
sq = mid * mid
if sq == x:
return mid
elif sq < x:
i = mid + 1
else:
j = mid - 1
return j
class Solution:
"""
@param: x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
# 牛顿迭代 1313ms
if x == 0:
return 0
last, res = 0, 1
while res != last:
last = res
res = (res + x/res)/2
return res