NOT getting all cases passed in the reverse the integer


#1

Can anyone suggest me the direct changes in my code so that I can handle the overflow cases
int Solution::reverse(int A) {
int rev = 0;
bool flag = false;
int prev = 0;
int d = 0;
if (A < 0)
{
A = -1 * A;
flag = true;
}
while (A != 0)
{
d = A%10;
rev = (rev*10) + d;
if ((rev - d)/10 != prev)
{
return 0;
}
prev = rev;
A = A/10;
}
return (flag == true) ? -rev : rev;
}


#2

There are some cases such as: 123000
for this your returned value should be: 321
Try to remove the terminating zeros don’t return 000321 for this
for negative cases such as: -123000
return: -321 not -000321


#3

You can hande overflow cases by simply checking it like this -
if (rev > (INT_MAX - (A%10))/10) return 0;
in the first line of the while loop.


#4

just add overflow and underflow condition before while loop
(int result >INT_MAX/10 || result <INT_MIN/10) return 0