题目:
Implementint sqrt(int x).
Compute and return the square root of x.
代码如下:
public class Solution {
public int sqrt(int x) {
if(x<=1)
return x;
int begin=1;
int end=x;
int mid=0;
while(begin<=end){
mid=begin+(end-begin)/2;
//如果写成mid*mid==x,会溢出
if(mid==x/mid){
return mid;
}else if(mid<x/mid){
begin=mid+1;
}else{
end=mid-1;
}
}
//结果返回end,end一定小于begin
return end;
}
}