Implement int sqrt(int x)
.
Compute and return the square root of x.
思路: 用二分法来运算。
易错点: 查找的时候用 long 来进行存储, 防止因为 int 过大造成溢出。
public class Solution {
public int sqrt(int x) {
if(x < 0)
return Integer.MIN_VALUE;
long mid = x;
long left = 0;
long right = x;
while(mid >= 0){
mid = (left + right) / 2;
long a = mid * mid;
long b = (mid + 1) * (mid + 1);
if(a <= x && b > x){
return (int)mid;
}
if(a > x){
right = mid - 1;
}else{
left = mid + 1;
}
}
return (int)mid;
}
}