Description:
Compute and return the square root of x.
Solution:
二分咯,但是对于l<r的判断,需要对x=0和1的情况进行特判。
import java.util.*;
public class Solution {
public int mySqrt(int x) {
if (x == 0 || x == 1)
return x;
long l = 0, r = x, mid;
while (l < r) {
mid = (l + r) / 2;
if (mid * mid <= x && (mid + 1) * (mid + 1) > x) {
return (int) mid;
}
if (mid * mid > x)
r = mid;
else
l = mid;
}
return (int) l;
}
}