leetcode-69. Sqrt(x)

题目:

Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
    Input: 4
    Output: 2
    Example 2:

    Input: 8
    Output: 2
Explanation: The square root of 8 is 2.82842..., and since
    the decimal part is truncated, 2 is returned.

思路:

牛顿迭代法, 导数方程 f'(x)*x'=y',  任何函数f(x)=y,求解某个y=n,均可以转化为 f(x)-n=0,
        此后就可以用牛顿迭代法,不断逼近实际待求x值。
        牛顿迭代共识:f'(x_pre)x_pre+x_pre=x_cur
应用: 迭代思想,类似于 动态规划思想,pre==>cur,进行动态推断处理
class Solution:
    def mySqrt(self, x):
        """
        :type x: int
        :rtype: int
        """
        r=x/2+1
        while r*r-x>1e-10:
            r=(r+x/r)/2
            # print(r*r-x)
    原文作者:龙仔
    原文地址: https://segmentfault.com/a/1190000015960027
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞