class Solution:
"""
@param: x: An integer
@return: The sqrt of x
"""
def sqrt(self, x):
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):
if x ==
0:
return 0
last, res =
0,
1
while res != last:
last = res
res = (res + x/res)/
2
return res