Problem description:

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [$−2^31$, $2^31 − 1$]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Solution:

need to check if the reversed number is overflow.
use a long long variable to store the reversed number.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int reverse(int x) {
long long tmp= 0;
int sign= x> 0? 1: -1;
x= abs(x);
while(x > 0){
tmp= tmp*10 +x%10;
x/=10;
}
return (tmp*sign< INT_MIN || tmp*sign> INT_MAX)? 0: tmp*sign;
}
};

time complexity: $O(n)$
space complexity: $O(1)$
reference:
https://goo.gl/zKDGQk