(LeetCode) 7. Reverse Integer

文章目录

  1. 1. Original URL: 7. Reverse Integer
  2. 2. My solutions:
    1. 2.1. With C++:
    2. 2.2. With Python2:
    3. 2.3. With Python3:

Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

Difficulty: Easy
Tags: Math

Original URL: 7. Reverse Integer

My solutions:

With C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int reverse(int x) {
int remain = x, reverse_x = 0;
while(remain)
{
reverse_x = (reverse_x + remain % 10 / 10.0) * 10;
remain = remain / 10;
}
if(reverse_x == INT_MIN)return 0;
else return reverse_x;
}
};

NOTE(2016/5/29):

When the reversed integer overflows,it turns to constant -2147483648(Minimum number of 32-bit binaries).In C++,the constant has been defined as INT_MIN.


With Python2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""

remain = x
reverse_x = 0
sign = 1
if(remain < 0):
sign = -1
remain *= -1
while(remain):
reverse_x = (reverse_x + remain % 10 / 10.0) * 10
remain = remain / 10
if(reverse_x > 0x7fffffff):
return 0
return int(reverse_x * sign)

NOTE(2016/5/30):

0x7fffffff is the constant 2147483647(Maximum number of 32-bit binaries).


With Python3:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def reverse(self, x):
remain = x
reverse_x = 0
sign = 1
if(remain<0):
sign = -1
remain *= -1
while(remain):
reverse_x = (reverse_x + remain % 10 / 10) * 10
remain = remain // 10
return int(reverse_x * sign)

UPDATE(2016/6/1):

The difference of division between Python2 and Python3:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!python2
>>> 12345 % 10
5
>>> 12345 / 10
1234
>>> 12345 / 10.0
1234.5
>>> 12345 // 10
1234

#!python3
>>> 12345 % 10
5
>>> 12345 / 10
1234.5
>>> 12345 / 10.0
1234.5
>>> 12345 // 10
1234

Besides,the reversed number will not overflow in Python.

See my 30+ solutions of LeetCode on GitHub