您的位置:首页 > 其它

[leetcode]Sqrt(x)

2014-08-08 00:05 357 查看

Sqrt(x)


Implement
int sqrt(int x)
.

Compute and return the square root of x.


【注意】:

1. 本题int类型可能会溢出,因此不能用乘法运算,应尽量用除法。

2. 绝大多数数字都不是可开方的,该如何得到比较近的结果呢?

算法思路:

思路1:顺序遍历肯定不需要试了,二分查找比较靠谱。二分法在数值计算中非常常见,需要熟练掌握。

代码如下:

public class Solution {
public int sqrt(int x) {
if(x <= 1) return x == 0 ? 0 : x;
int l = 1, r = x /2 + 1 ;
while(l <= r){
int mid = (l + r) / 2;
if(mid <= x / mid && (mid + 1) > x / (mid + 1)){
return mid;//这里用的很巧妙
}else if(mid > x / mid){
r = mid - 1;
}else{
l = mid + 1;
}
}
return 0;
}
}


思路2:牛顿迭代法;比较高大上,详细分析过程请戳这里

代码如下:  

public int sqrt(int x) {
if (x == 0) return 0;
double lastY = 0;
double y = 1;
while (y != lastY)
{
lastY = y;
y = (y + x / y) / 2;
}
return (int)(y);
}


这道题出的很好
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: