LeetCode Sqrt (x)

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.