update 69
This commit is contained in:
parent
fd5fc4ace5
commit
dfa7820a1c
22
leetcode/69.py
Normal file
22
leetcode/69.py
Normal file
@ -0,0 +1,22 @@
|
||||
# Sqrt(x)
|
||||
# Do not use build in operator
|
||||
|
||||
|
||||
class Solution:
|
||||
def mySqrt(self, c: int) -> int:
|
||||
# Use Newton's method, return the smaller root
|
||||
# fx = x ** 2 - c
|
||||
# Xn-1 = 0.5 * (Xn + c / Xn)
|
||||
x = c / 2
|
||||
while True:
|
||||
next_x = (x + c / x) / 2
|
||||
if x - next_x > -1 and x - next_x <= 0:
|
||||
break
|
||||
x = next_x
|
||||
|
||||
return int(x)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(Solution().mySqrt(13))
|
||||
print(Solution().mySqrt(16))
|
Loading…
x
Reference in New Issue
Block a user