您的位置:首页 > 编程语言 > Java开发

(Java)LeetCode-69. Sqrt(x)

2016-11-03 16:02 549 查看
Implement 
int sqrt(int x)
.

Compute and return the square root of x.

这道题么,当然最简单的方法就是一行代码  return(int)Math.sqrt(x);

不过出于强迫症,还是用二分法又写了一遍代码。需要注意的地方是循环应该是while(left <= right) 而不是 while(left < right) 因为当left == right的时候可能也不是答案,偏大了,这时候right会-1,返回right即可。代码如下:

public int mySqrt(int x) {
int left =0;
int right = x/2+1;
long mid = 0; //the long type prevent the overflow of int
while(left <= right){
mid = (left + right)/2;
System.out.println(left+" "+ right+" "+mid);
if(mid * mid == x){ // if mid is int , here may be fault
return (int)mid;
}else if(mid * mid > x){
right = (int)mid-1;
}else{
left = (int)mid+1;
}
}
return right;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Math Binary Search