7.Reverse Integer

Question:

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

Example3: x = 120, return 21

Note:Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

My answer in Java:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public int reverse(int x) {
int res=0;
if(x==0)
return x;
while(x!=0){
res=res*10+x%10;
x=x/10;
}
return res;
}
}

Better answer in Java:

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

Didn’t thought about over integer overflows, why this problem will happen, we know that the range of integer is -2147483648~2147483647. So if we want to traverse the integer 1000000009, the traversed number 9000000001 will be out of range, so we need to judge the overflow situation.

Answer in python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution(object):
# def reverse(self, x):
# """
# :type x: int
# :rtype: int
# """
# res=0
# if x==0:
# return 0
# while x!=0:
# res=res*10+x%10
# x=x/10
# return res if -2147483648 <= res <= 2147483647 else 0
def reverse(self, x):
s = str(x)
res = int('-' + s[1:][::-1]) if s[0] == '-' else int(s[::-1])
return res if -2147483648 <= res <= 2147483647 else 0

But I have a consider is that why the code which are annotated can’t not run when the input integer is -321