您的位置:首页 > 其它

Sqrt(x) 求平方根@LeetCode

2013-11-11 02:58 423 查看
二分法

package Level4;

/**
* Sqrt(x)
*
* Implement int sqrt(int x).
*
* Compute and return the square root of x.
*
*/
public class S69 {

public static void main(String[] args) {
System.out.println(sqrt(2));
}

public static int sqrt(int x) {
double diff = 0.01; // 误差
int low = 0;
int high = x;

while(low <= high){
// 注意越界!所以用double来存
double mid = low + (high-low)/2;
if(Math.abs(mid*mid-x) <= diff){
return (int)mid;
}else if(x > mid*mid+diff){
low = (int)mid+1;
}else if(x < mid*mid-diff){
high = (int)mid-1;
}
}

// 当找不到时候,这是low,high指针已经交叉,取较小的,即high
return high;
}

}

public class Solution {
public int sqrt(int x) {
int left = 0, right = x;
while(left <= right) {
double mid = left + (right-left)/2;
double mul = mid * mid;
if(mul == x){
return (int)mid;
} else if(mul < x) {
left = (int)mid+1;
} else {
right = (int)mid-1;
}
}
return right;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: