diff --git a/leetcode/69.py b/leetcode/69.py new file mode 100644 index 0000000..a5739a1 --- /dev/null +++ b/leetcode/69.py @@ -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))