class Solution {
public:
int mySqrt(int x) {
return binarySearch(1, x, x);
}
private:
int binarySearch(long left, long right, long target) {
if (left > right) {
return 0;
}
long mid = (left + right) / 2;
long x = target / mid;
if (mid == x) {
return mid;
}
if (x > mid) {
if (x - mid == 1) {
return mid;
}
return binarySearch(mid + 1, right, target);
} else {
if (mid - x == 1) {
return x;
}
return binarySearch(left, mid - 1, target);
}
}
};