当前位置:网站首页>[LeetCode] 整数反转【7】
[LeetCode] 整数反转【7】
2022-07-05 04:55:00 【山茶花开时。】
问题: 给你一个32位的有符号整数x,返回将x中的数字部分反转后的结果
如果反转后整数超过32位的有符号整数的范围[-(2**31), 2**31-1] ,就返回0
示例1
输入: x = 123
输出: 321
示例2
输入: x = -123
输出: -321
示例3
输入: x = 120
输出: 21
示例4
输入: x = 0
输出: 0
# 解法1
def reverse(x):
if x == 0:
return 0
if x > 0:
str_x = str(x)
str_x = str_x[::-1]
x = int(str_x)
if x > 2**31 - 1:
return 0
if x < 0:
str_x = str(x)
str_x = str_x[1:]
str_x = str_x[::-1]
x = '-' + str_x
x = int(x)
if x < -(2**31):
return 0
return x
# 解法2
def reverse(x):
if x == 0:
return 0
else:
str_x = str(x)
# 判断x为负数的情况
if str_x[0] == '-':
str_x = '-' + str_x[-1:-len(str_x):-1]
if int(str_x) < -(2**31):
return 0
else:
# 判断x为正数的情况
str_x = str_x[-1:- (len(str_x) + 1 ):-1]
if int(str_x) > 2**31 - 1:
return 0
return(int(str_x))
边栏推荐
猜你喜欢
669. Prune binary search tree ●●
49 pictures and 26 questions explain in detail what is WiFi?
Introduce Hamming distance and calculation examples
Recherche de mots pour leetcode (solution rétrospective)
[goweb development] Introduction to authentication modes based on cookies, sessions and JWT tokens
3dsmax scanning function point connection drawing connection line
Pdf to DWG in CAD
[Business Research Report] top ten trends of science and technology and it in 2022 - with download link
Emlog博客主题模板源码简约好看响应式
Redis has four methods for checking big keys, which are necessary for optimization
随机推荐
Detailed introduction of OSPF header message
Fluent objects and lists
Use assimp library to read MTL file data
Judge the position of the monster in the role under unity3d
[groovy] closure closure (customize closure parameters | customize a single closure parameter | customize multiple closure parameters | specify the default value of closure parameters)
How much do you know about 3DMAX rendering skills and HDRI light sources? Dry goods sharing
Research and investment forecast report of adamantane industry in China (2022 Edition)
Emlog blog theme template source code simple good-looking responsive
Manually implement heap sorting -838 Heap sort
AutoCAD - command repetition, undo and redo
JVM 原理和流程简介
[groovy] closure (closure as function parameter | code example)
Autocad-- dynamic zoom
Introduction to JVM principle and process
SQL set operation
"Measuring curve length" of CAD dream drawing
How to choose a panoramic camera that suits you?
2021 higher education social cup mathematical modeling national tournament ABCD questions - problem solving ideas - Mathematical Modeling
Create a pyGame window with a blue background
[groovy] closure (closure parameter list rule | default parameter list | do not receive parameters | receive custom parameters)