Why does my code not handle negative numbers for reversing?

My program takes an integer negative or positive and outputs the reverse. If the reverse overflows or underflows it returns 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <climits> 
#include <limits.h>
using namespace std;

/**
 * PURPOSE: displays reverse of the number or a 0 if it overflows. 
 * PARAMETERS:
 *     int 
 * RETURN VALUES:
 *     reverse of integer input. 
*/



int main() {
    int n, reverse = 0;
    bool invalid = false;
    
    cout << "Enter an integer: ";
    cin >> n;
     while(n ) {
        int oldVal = reverse;
        int remainder = n%10;
        reverse = reverse*10 + remainder;
        if (reverse < oldVal) {
            invalid = true;
            break;
            
        }
        n/=10;
    }
       if(invalid) 
       cout <<"0" << endl; 
       else 
       cout <<reverse << endl;
    
    return 0;
}
When you enter -11 the value of reverse is -1 and oldVal is 0
1
2
3
4
5
if (reverse < oldVal) 
{
   invalid = true;
   break;
}
I know it doesn't work. But how do I fix it.
If it's negative, make it positive, find the reverse, and then make that negative.

I'm assuming that you want, for example, -91 to be reversed to -19.
I changed it to something that works with negative or positive, but doesn't work for overflow. It does not return 0 on overflow like it's supposed to because I used a long.
#include <iostream>

using namespace std;

class Operations
{
long c;

public:
void inputNumber()
{
cout << "Input a number\n";
cin >> c;
}

long reverseNumber()
{
long invert = 0;

while (c != 0)
{
invert = invert * 10;
invert = invert + c%10;
c = c/10;
}

return invert;
}

};

int main()
{
long result;

Operations t;
t.inputNumber();
result = t.reverseNumber();

cout << "Number obtained on reversal = " << result << endl;

return 0;
}
Topic archived. No new replies allowed.