Porblem:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Analysis:
The basic idea is to fetch the first digit of the integer one by one, and form a new integer by the reverse order.
Solution:
C++:
int reverse(int x) {
unsigned int temp_x;
bool isNegative = false;
if(x == 0)
return 0;
else if(x < 0) {
temp_x = (-1) * x;
isNegative = true;
} else
temp_x = x;
int rInt = 0;
const int bound = 214748364;
while(1) {
int reminder = temp_x % 10;
rInt = rInt*10 + reminder;
temp_x = (temp_x - reminder) / 10;
if(temp_x == 0)
break;
if(rInt > bound)
return 0;
}
if(isNegative)
return (-1)*rInt;
return rInt;
}
Java:
Python: