I've been struggling with this for quite a while. I want to solve it using a binary search, and my code is quite straightforward, and I think, correct:
if (x < 0) {
return -1;
}
if (x == 0 || x == 1) {
return x;
}
int start = 1;
int end = x;
while (start<=end) {
int mid = start+ (end-start)/2;
if (mid*mid<=x && (mid+1)*(mid+1)>x) return mid;
if(mid*mid>x) {
end = mid-1;
} else {
start = mid+1;
}
}
return 0;
Of course, it fails for 2147483647 case, because mid*mid
causes integer overflow. I've tried dealing with long
instead:
long tmp = mid*mid;
long tmp1 = (mid+1)*(mid+1)
if (tmp<=x && tmp1>x) return mid;
However, I get time limit exceeded, because even that overflows.
How to deal with situations like this? What am I missing?