LeetCode 筆記 - 7. Reverse Integer

題目在此 7. Reverse Integer

將數字反轉

解題思維

給定一個數字,將數字反轉。

Time complexity: O(1)

程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
def reverse(self, x: int) -> int:

x = str(x)
if len(x) < 2:
return x

if x.startswith('-'):
x = x[::-1]
x = f'-{x[:-1]}'
else:
x = x[::-1]

x = int(x)

# overflow
if x >= 2147483651:
return 0
if x <= -2147483651:
return 0
return x

也許你也會想看看