Skip to content

Commit f5c00c7

Browse files
committed
[Add] Leetcode > 7. Reverse Integer
1 parent 44751a6 commit f5c00c7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Leetcode/reverse_integer.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 7. Reverse Integer
2+
3+
# (1) 정수 사용하기 (54 ms)
4+
class Solution:
5+
def reverse(self, x: int) -> int:
6+
if x < 0:
7+
sign = -1
8+
x = -x
9+
else:
10+
sign = 1
11+
12+
result = 0
13+
while x:
14+
result = (result * 10) + (x % 10)
15+
x = x // 10
16+
17+
if -2**31 > result or 2**31 - 1 < result:
18+
return 0
19+
20+
return result * sign
21+
22+
# (2) 문자열 사용하기 (37 ms)
23+
class Solution:
24+
def reverse(self, x: int) -> int:
25+
if x < 0:
26+
sign = -1
27+
x = -x
28+
else:
29+
sign = 1
30+
31+
x_string = str(x)
32+
result_string = x_string [::-1]
33+
result = int(result_string)
34+
35+
if -2**31 > result or 2**31 - 1 < result:
36+
return 0
37+
38+
return result * sign

0 commit comments

Comments
 (0)