lintcode:x的平方根

xiaoxiao2021-02-28  99

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
转载请注明原文地址: https://www.6miu.com/read-44893.html

最新回复(0)