leetcode题解-69. x 的平方根

Ingrid ·
更新时间:2024-09-21
· 888 次阅读

问题
实现 int sqrt(int x) 函数。
计算并返回 x 的平方根,其中 x 是非负整数。
由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。
示例 1:

输入: 4
输出: 2

示例 2:

输入: 8
输出: 2

说明: 8 的平方根是 2.82842…,
由于返回类型是整数,小数部分将被舍去。

来源:力扣(LeetCode)
链接:69. x 的平方根
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

分析
如果学过数值分析的话。可以用牛顿迭代法来求平方根,对于x=a2x=a^2x=a2相应的迭代公式为an+1=(an+xan)2a_{n+1}=\frac {(a_n+\frac{x}{a_n})} {2}an+1​=2(an​+an​x​)​

代码

public static int mySqrt(int x) { //迭代初值一般取x/2 double a0=x/2.0,a1=(a0+x/a0)/2.0; //精度越大越好,这里取1.0e-10 while(Math.abs(a1-a0)>1.0e-10){ a0=a1; a1=(a0+x/a0)/2.0; } //取a1和a0均可 return (int)a1; }

在这里插入图片描述
2020.04.13


作者:ataraxy_thinking



leetcode 平方根

需要 登录 后方可回复, 如果你还没有账号请 注册新账号