当前位置:网站首页>[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))边栏推荐
- Introduce Hamming distance and calculation examples
- Flink cluster configuration
- AutoCAD - workspace settings
- Common database statements in unity
- 【acwing】836. Merge sets
- 2021 electrician cup idea + code - photovoltaic building integration plate index development trend analysis and prediction: prediction planning issues
- PostgreSQL 超越 MySQL,“世界上最好的编程语言”薪水偏低
- Basic knowledge points
- An article takes you to thoroughly understand descriptors
- 中国AS树脂市场调研与投资预测报告(2022版)
猜你喜欢

用 Jmeter 工具做个小型压力测试

Leetcode word search (backtracking method)

次小生成树

【acwing】836. Merge sets

Pdf to DWG in CAD

Download the details and sequence of the original data access from the ENA database in EBI

【Leetcode】1352. Product of the last K numbers

AutoCAD - feature matching

"Measuring curve length" of CAD dream drawing

Minor spanning tree
随机推荐
2021 electrician cup idea + code - photovoltaic building integration plate index development trend analysis and prediction: prediction planning issues
3dsmax common commands
2021 electrician Cup - high speed rail traction power supply system operation data analysis and equivalent modeling ideas + code
计组笔记(1)——校验码、原补码乘除计算、浮点数计算
MySQL audit log archiving
AutoCAD -- dimension break
Use assimp library to read MTL file data
2021 electrician cup (the 12th "China Society of electrical engineering Cup" National Undergraduate electrician mathematical modeling) detailed ideas + codes + references
Database under unity
【acwing】528. cheese
【Leetcode】1352. 最后 K 个数的乘积
This article is good
Detailed explanation of the ranking of the best universities
#775 Div.1 C. Tyler and Strings 组合数学
54. 螺旋矩阵 & 59. 螺旋矩阵 II ●●
The difference between bundle, chunk and module
PostgreSQL surpasses mysql, and the salary of "the best programming language in the world" is low
China needle coke industry development research and investment value report (2022 Edition)
質量體系建設之路的分分合合
[groovy] closure (closure parameter list rule | default parameter list | do not receive parameters | receive custom parameters)