Skip to content

Commit c6369b7

Browse files
Create 7. Reverse Integer QuestionEditorial Solution
1 parent 952d226 commit c6369b7

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
'''
2+
Reverse digits of an integer.
3+
4+
Example1: x = 123, return 321
5+
Example2: x = -123, return -321
6+
7+
'''
8+
9+
class Solution(object):
10+
def reverse(self, x):
11+
res = int(str(abs(x))[::-1])
12+
if x < 0:
13+
res = -res
14+
if res > 2147483647 or res < -2147483648:
15+
res = 0
16+
return res
17+
# without str()
18+
def reverse2(self, x): from math import log
19+
if x < 10 and x > -10:
20+
return x
21+
flipped = False
22+
if x < 0:
23+
flipped = True
24+
x *= -1
25+
res = 0
26+
log10 = int(log(x, 10))
27+
for i in xrange(log10 + 1):
28+
digit = x % 10
29+
res += digit * 10**(log10 - i)
30+
x /= 10
31+
if res > 2**31 - 1 or res < -1 * 2**31 + 1:
32+
return 0
33+
if flipped:
34+
res *= -1
35+
return res

0 commit comments

Comments
 (0)