【力扣】整数反转
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-integer
给你一个 32 位的有符号整数 x ,返回 x 中每位上的数字反转后的结果。
如果反转后整数超过 32 位的有符号整数的范围 $[−2^{31}, 2^{31} − 1]$ ,就返回 0。
假设环境不允许存储 64 位整数(有符号或无符号)。
示例 1:
输入:x = 123
输出:321
示例 2:
输入:x = -123
输出:-321
示例 3:
输入:x = 120
输出:21
示例 4:
输入:x = 0
输出:0
1 class Solution: 2 def reverse(self, x: int) -> int: 3 if x == 0: 4 return x 5 elif x<0: 6 str_x = str(x) 7 str_x=str_x[:0:-1] 8 x = int(str_x) 9 x = -x 10 if x>=(-2**31): 11 return x 12 else: 13 return 0 14 elif x>0: 15 str_x = str(x) 16 str_x=str_x[::-1] 17 x = int(str_x) 18 if x<=(2**31-1): 19 return x 20 else: 21 return 0
主要熟悉切片操作。
                    
                
                
            
        
浙公网安备 33010602011771号