This code is used to reverse a number in C++ but I have a problem.
When I input 1010 or -1010, the output is -101 and 101.
How should I fix this?
/* Christopher Langford U05799189
* clang4d@gmail.com
* Assignment 3 Exercise 3
* July 23, 2010
* Macbook Pro w/Mac OSX 10.6.3
* Xcode Version 3.2.2
* C/C++ Programming 1, Section ID077588
* This takes an integer and returns it in an English representation
*/
#include <iostream>
const int BASE = 10; /* Instead of a "magic number" used to reverse digits */
using namespace std;
int main()
{
int reverse_num(int sourcenum);
/* Variables */
int num;
cout << "This program will reverse any integer number entered by the user. \n";
cout << "Enter the integer to be reversed: \n";
cin >> num;
reverse_num(num); /* call the function reverse_num */
return 0;
}
int reverse_num(int sourcenum)
{
int temp = sourcenum;
int sum = 0;
while (temp)
{
sum *= BASE; /* used to produce the least significant decimal integral value */
sum += temp % BASE;
temp /= BASE; /* used to elimitate that digit from the value */
}
cout << "Your integer reversed is: " << sum << '\n';
return sum;
}