Pay attention to that mid * mid may be larger than int. So long long is enough.
class Solution {
public:
int sqrt(int x) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int l = 0, r = x;
while (l <= r) {
int mid = (l + r) / 2;
long long mid2 = (long long)mid * (long long)mid;
long long mid12 = (long long)(mid + 1) * (long long)(mid + 1);
if (mid2 <= x && mid12 > x)
return (int)mid;
if (mid2 > x)
r = mid -1;
else
l = mid +1;
}
}
};