”’
@greg 2017-08-24
Implement int sqrt(int x).
Compute and return the square root of x.
求解整数的平方根
class Solution():
def mySqrt(self, x):
'''
当前值的平方小于x,下一个值的平方大于x,所以就返回x
:param x:
:return:
'''
if x == 1:
return 1
if x == 0:
return 0
half_x = x // 2
for i in range(1, half_x+1):
if i**2 <= x and (i+1) ** 2 > x:
return i
def mySqrt1(self, x):
'''
g的更新方式为g = (g + x / g) / 2
迭代法求解
:param x:
:return:
'''
g = x
while g*g-x > 0:
g = (g + x / g) / 2
return int(g)
if __name__ == '__main__':
s = Solution()
x = 3
print(s.mySqrt1(x))