Arunava Nag - 6 months ago 40

C++ Question

Hello I am trying a simple reverse integer operation in c++. Code below:

`#include <iostream>`

#include <algorithm>

#include <climits>

using namespace std;

class RevInteger {

public:

int reverse(int x)

{

int result = 0;

bool isNeg = x > 0 ? false : true;

x = abs(x);

while (x != 0)

{

result = result * 10 + x % 10;

x = x / 10;

}

if (isNeg)

result *= -1;

if (result > INT_MAX || result < INT_MIN)

return 0;

else

return (int)result;

}

};

When I give it an input as 1534236469; I want it to return me 0, instead it returns me some junk values. What is wrong in my program. Also, I am trying to use the climits lib for the purpose, is there a simpler way of doing the same?

Answer

The simplest approach is to use `long long`

in place of `int`

for the result, and check for overflow at the end:

```
long long result = 0;
/* the rest of your code */
return (int)result; // Now the cast is necessary; in your code you could do without it
```

Another approach is to convert the `int`

to string, reverse it, and then use the standard library to try converting it back, and catch the problems along the way (demo):

```
int rev(int n) {
auto s = to_string(n);
reverse(s.begin(), s.end());
try {
return stoi(s);
} catch (...) {
return 0;
}
}
```

If you must stay within integers, an approach would be to check intermediate result before multiplying it by ten, and also checking for overflow after the addition:

```
while (x != 0) {
if (result > INT_MAX/10) {
return 0;
}
result = result * 10 + x % 10;
if (result < 0) {
return 0;
}
x = x / 10;
}
```