[Leetcode] Sqrt(x) (Java)
来源:互联网 发布:matlab怎么创建空矩阵 编辑:程序博客网 时间:2024/05/28 04:53
Implement int sqrt(int x)
.
Compute and return the square root of x.
实现求根
牛顿迭代法(参考)
为了方便理解,就先以本题为例:
计算x2 = n的解,令f(x)=x2-n,相当于求解f(x)=0的解,如左图所示。
首先取x0,如果x0不是解,做一个经过(x0,f(x0))这个点的切线,与x轴的交点为x1。
同样的道理,如果x1不是解,做一个经过(x1,f(x1))这个点的切线,与x轴的交点为x2。
以此类推。
以这样的方式得到的xi会无限趋近于f(x)=0的解。
判断xi是否是f(x)=0的解有两种方法:
一是直接计算f(xi)的值判断是否为0,二是判断前后两个解xi和xi-1是否无限接近。
经过(xi, f(xi))这个点的切线方程为f(x) = f(xi) + f’(xi)(x - xi),其中f'(x)为f(x)的导数,本题中为2x。令切线方程等于0,即可求出xi+1=xi - f(xi) / f'(xi)。
继续化简,xi+1=xi - (xi2 - n) / (2xi) = xi - xi / 2 + n / (2xi) = xi / 2 + n / 2xi = (xi + n/xi) / 2。
有了迭代公式xi+1= (xi + n/xi) / 2,程序就好写了。
public class Solution { public int sqrt(int x) { if(x==1)return 1;double res = x/2;while(Math.abs(res*res-x)>0.00001){res=(res+x/res)/2;}return (int) res; }}
0 0
- [Leetcode] Sqrt(x) (Java)
- Sqrt(x) -- LeetCode (Java)
- [LeetCode][Java] Sqrt(x)
- leetcode:Sqrt(x) 【Java】
- (Java)LeetCode-69. Sqrt(x)
- 【leetcode】69. Sqrt(x)【java】
- Sqrt(int x) leetcode java
- LeetCode Sqrt(x) 整数平方根 java
- leetcode oj java 69. Sqrt(x)
- LeetCode: Sqrt(x)
- LeetCode sqrt(x)
- [Leetcode] Sqrt(x)
- LeetCode :Sqrt(x)
- leetcode 53: Sqrt(x)
- [LeetCode] Sqrt(x)
- Leetcode 69 sqrt(x)
- [Leetcode] Sqrt(x)
- leetcode:Sqrt(x)
- 黑马程序员-java学习笔记-银行业务调度系统
- FTPClient连接FTP服务器进行简单FTP操作
- 阿里云服务使用感受
- 网络异常检查-3A--多种心跳检测机制,解决异常
- 空心字HollowFont
- [Leetcode] Sqrt(x) (Java)
- ubuntu 10.04 下载源列表
- 谈程序员的技术情结
- 2013年终考核
- zoj 1005 Jugs (模拟)
- 2014版前端设计学习路线
- 多核网络处理器媒体面软件架构探讨——同步流水线架构
- swing jTree 绑定数据库
- UIView之userInteractionEnabled属性介绍