# [leetcode] Reverse Integer

### Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

click to show spoilers.

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):

tag: math

9/25/2015 update

```//how to deal with overflow?
//0 should be reversed to 0
//10000 => 1
class Solution {
public:
int reverse(int x) {
int flag = x < 0? -1: 1;
x = x * flag;
long ans = 0;
while(x / 10){
int digit = x % 10;
ans = ans * 10 + digit;
x = x / 10;
}
ans = ans * 10 + x;
ans = ans * flag;
if(ans < (int)0x80000000 || ans > (int)0x7fffffff){
ans = 0;
}
return (int)ans;
}
};```

Leetcode上有很多关于math的题，都被标为了easy，虽然我并不认为math的题简单，即使不涉及任何复杂的数据结构，但却足以做成脑筋急转弯。

Leetcode官方solution给出了一种解法。

To check for overflow/underflow, we could check if ret > 214748364 or ret < –214748364 before multiplying by 10. On the other hand, we do not need to check if ret == 214748364, why?

```class Solution {
public:
int reverse(int x) {
long long maxNum = 0x7FFFFFFF;//2147483647
string s = to_string(x);
reverse(s);
long long reversedNum = stoll(s);
if (reversedNum > maxNum || reversedNum < -maxNum){
return 0;
}
else{
return (int)reversedNum;
}
}
void reverse(string& s){
int start = 0;
int end = s.size() - 1;
if(s[0] == '-'){
start = 1;
end = s.size();
}
for(int i = start; i < end - i; i++){
char tmp = s[i];
s[i] = s[end - i];
s[end - i] = tmp;
}
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.