LeetCode Sqrt (x)
Sqrt (x) for solving LeetCode Problems)
Original question
Returns the square root of a number.
Note:
Returns an integer, excluding decimal places, not rounded.
Example:
Input: x = 5
Output: 2
Solutions
Use Newton iteration method to obtain the Equation Through ApproximationY = x ^ 2 +. Next, we will introduce the Newton Iteration Method. For example, finding the intersection between the equation curve and the Y axis is the solution of the equation. Random ValueX0, Find the curve inX0The tangent. The intersection of the tangent and the Y axis isX1, And then try againX1It can be seen that the intersection is constantly approaching the target value, and now you can find an approximate solution by determining a threshold value. Because the square root is a positive number, the initial value should be a positive number.
Note: images are from search engines.
AC Source Code
Class Solution (object): def mySqrt (self, x): "": type x: int: rtype: int "result = 1.0 while abs (result * result-x)> 0.1: result = (result + x/result)/2 return int (result) if _ name _ = "_ main _": assert Solution (). mySqrt (5) = 2 assert Solution (). mySqrt (0) = 0