当前位置:网站首页>[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))边栏推荐
- AutoCAD - Center zoom
- PostgreSQL 超越 MySQL,“世界上最好的编程语言”薪水偏低
- Unity parallax infinite scrolling background
- 质量体系建设之路的分分合合
- 【Leetcode】1352. 最后 K 个数的乘积
- [groovy] closure (closure parameter binding | curry function | rcurry function | ncurry function | code example)
- Autocad-- dynamic zoom
- 2021 Higher Education Club Cup mathematical modeling national tournament ABCD problem - problem solving ideas
- AutoCAD - stretching
- 2021-10-29
猜你喜欢

LeetCode之單詞搜索(回溯法求解)

2021-10-29

2022 thinking of Mathematical Modeling B problem of American college students / analysis of 2022 American competition B problem

AutoCAD -- dimension break

669. 修剪二叉搜索树 ●●

3dsmax scanning function point connection drawing connection line

【acwing】528. cheese

AutoCAD - isometric annotation

Solutions and answers for the 2021 Shenzhen cup

Flutter 小技巧之 ListView 和 PageView 的各种花式嵌套
随机推荐
[groovy] closure (closure as function parameter | code example)
中国金刚烷行业研究与投资预测报告(2022版)
数论函数及其求和 待更新
C iterator
[PCL self study: feature9] global aligned spatial distribution (GASD) descriptor (continuously updated)
2022 U.S. college students' mathematical modeling e problem ideas / 2022 U.S. game e problem analysis
Establish cloth effect in 10 seconds
mysql審計日志歸檔
MD5 bypass
Leetcode word search (backtracking method)
Minor spanning tree
Variable category (automatic, static, register, external)
2020-10-27
Download the details and sequence of the original data access from the ENA database in EBI
中国AS树脂市场调研与投资预测报告(2022版)
Function template
Inline built-in function
Introduction to JVM principle and process
AutoCAD - set layer
PR first time