I was trying to solve the reverse integer problem, where we have to keep in mind to deal with overflow.
Reading others solutions and tried out, I wrote my solution
class Solution {
public:
int reverse(int x) {
int result = 0;
int old_result = 0;
while(x) {
old_result = result;
result = result*10 + x%10;
if ((result-old_result*10)!=x%10)
return 0;
x = x/10;
}
return result;
}
};
And the answer was not accepted because overflow was not handled well. It turned out changing
if ((result-old_result*10)!=x%10)
to
if ((result-x%10)/10!=old_result)
would make things work.
I feel these lines are doing the same check. Not sure why one passes and one fails.
Can anyone help explain?