11.2 Sqrt(x)
来源:互联网 发布:it公司招人难 编辑:程序博客网 时间:2024/06/05 02:15
Approach I: Binary Search.
The sqrt(x) can be not larger than x/2+1. //why?
Time: O(logn), Space: O(1)
public class Solution { public int sqrt(int x) { if(x < 2) return x;//what if x <0? int l = 1; int r = x/2 + 1; while(l <= r){ int m = (l+r)/2; if(x/m>=m && x/(m+1)<m+1){//x is between [m^2, (m+1)^2) return m; } else if(x/m < m){//x < m^2 r = m-1; } else{//x > (m+1)^2 l = m+1; } } return 0; }}
Approach II: Newton Method
//why res = 1?
public class Solution { //Newton method public int sqrt(int x) { if(x == 0) return 0; double last = 0; double res = 1;//why? while(res != last){ last = res; res = (res + x/res)/2; } return (int) res; }}
0 0
- 11.2 Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- sqrt(x)
- Sqrt(x)
- sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- Sqrt(x)
- JPA 复合主键
- mac下调整eclipse控制台的编码
- 胜利大逃亡(三维BFS)
- 心电的具体含义?
- 集成测试
- 11.2 Sqrt(x)
- 心电是什么意思?
- NavigationBar 的学习,写给新手的福利
- JAX-RS入门 一 :基础
- WordPress搬家教程
- 中国剩余定理详解
- sF的施工方讀後感房間的說法
- poj2431 Expedition(优先队列和贪心)
- 后金融危机时代中小企业信息化建设何去何从