Implement int sqrt(int x)
.
Compute and return the square root of x.
用二分法来查找,x的根肯定是大于0小于x的,mid作为x的根,用mid * mid与x比大小,然后接着查找,如果有则返回,不能开尽的用较小的整数代替(根向下取整)。
Source
public class Solution {
public int sqrt(int x) {
long low = 0, high = x; //int型在mid*mid会溢出
while(low <= high){
long mid = (low + high) / 2;
if(mid * mid < x){
low = mid + 1 ;
}
else if(mid * mid > x){
high = mid - 1;
}
else return (int)mid;
}
return (int)high; //测试数据可以看出希望返回的是较小的那个数,跳出循环的时候是low>high 所以high指向较小的
}
}
Test
public static void main(String[] args){
System.out.println(new Solution().sqrt(2));
}