The idea is to binary try square and adjust high or low based on comparison. Instead of using recursive, iteration is used here for binary search: if low + 1 < high, high=mid/low=mid/return.
Notice that the while condition mush be high - low > 1, as the case 2 will cause loop forever if using h>l only!
public class Solution {
public int sqrt(int x) {
if(x <= 0){
return 0;
}
if(x == 1){
return 1;
}
long low = 1;
long high = x;
long mid = (low + high) / 2;
while(high - low > 1){
mid = (low + high) / 2;
if(mid * mid > x){
high = mid;
}else if(mid * mid < x){
low = mid;
}else{
return (int)mid;
}
}
return (int)low;
}
}
没有评论:
发表评论