# LeetCode题目：Reverse Integer

By | 2012 年 10 月 18 日

Reverse Integer
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?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

```class Solution {
public:
int reverse(int x) {
int sup = 1;
{//find the most significant bit
int temp = x;
while(temp /= 10) {
sup *= 10;
}
}
int sub = 10;
int y = 0;//result
while(sup >= sub) {
int dsup = x / sup;
int dsub = (x % sub) / (sub / 10);
//cout<<dsup<<","<<dsub<<",";
x -= sup * dsup;
x -= (sub / 10) * dsub;
//cout<<x<<"|";
y += sup * dsub;
y += (sub / 10) * dsup;

sup /= 10;
sub *= 10;
}
if (sup * 10 == sub) {
y += x;
}
return y;
}
};
```

## One thought on “LeetCode题目：Reverse Integer”

1. Pingback: LeetCode: Reverse Integer – uniEagle