Hello, I am trying some leetcode problems but couldnt solve it and had to look at the solution. But I am a bit confused with it. Mostly the 2 lines with INT_MAX and INT_MIN. I understand that these are the max and min that an int can be, but I just cant figure out how it is working in this piece of code, especially with the >7 and <8.
If possible could someone please explain this to me
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int reverse(int x)
{
int rev = 0;
while (x != 0) {
int pop = x % 10;
cout <<"pop " << pop << "\n";
x /= 10;
cout << "x " << x << "\n";
if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
cout << "rev " << rev << "\n";
}
return rev;
}
the return zeros are error handling of sorts.
if its > int max / 10, then multiply by 10 on line 11 won't work right, so it quits.
if its < int min/10 you have a similar problem with a negative number.
the 7 and 8 are hard coded looking at the issue bit-wise. If you don't see it, look at an 8 bit number and it will pop out, its a lot of typing 1s and 0s to show...
It's basically to detect numeric overflow and underflow.
And because it's trying to reverse a number, the 7 and -8 come from the least significant digit of the number (which is about to become the most significant digit of the number).