#9 上传文件至 ''

Merged
1030514181 merged 1 commits from 1030514181-patch-5 into master 1 year ago
  1. +31
    -0
      7-整数反转.py

+ 31
- 0
7-整数反转.py View File

@@ -0,0 +1,31 @@
'''
【中等】
给你一个 32 位的有符号整数 x ,返回将 x 中的数字部分反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 [−231,  231 − 1] ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
'''
class Solution:
def reverse(self, x: int) -> int:
list_x = []
result_x = 0
flag = 0
if x < 0:
x = abs(x)
flag = 1
while x // 10:
list_x.append(x % 10)
x //= 10
list_x.append(x)
for i in list_x:
result_x = result_x * 10 + i
if flag:
result_x = - result_x
if result_x < - 2 ** 31 or result_x > 2 ** 31 - 1:
return 0
return result_x

Loading…
Cancel
Save