class Solution {
public int mySqrt(int x) {
if (x == 0) return 0;
if (x == 1) return 1;
int l = 0, r = x;
while (l <= r) {
int mid = l + (r - l) / 2;
long tmp = (long) mid * (long) mid;
if (tmp < (long) x) {
l = mid + 1;
} else if (tmp > (long) x) {
r = mid - 1;
} else {
return mid;
}
}
return l - 1;
}
}