题意理解:
实现sqrt()函数;
题目分析:
1. 典型的二分法;
2. 注意使用long保留中间值,避免整数相乘出现溢出;
解题代码:
public class Solution {
private int process(int left, int right, int val){
//System.out.println("left= "+left+" right= "+right);
if(right-left==1){
return left;
}
int half=left+(right-left)/2;
long tmp=half;
tmp*=tmp;
//System.out.println("tmp= "+tmp);
if(tmp==val){
return half;
}if(tmp>val){
return process(left, half, val);
}else{
return process(half, right, val);
}
}
public int mySqrt(int x) {
if(x==1 || x==0){
return x;
}
return process(1, x, x);
}
}