题目描述
Given a 32-bit signed integer, reverse digits of an integer.
- Example 1:
Input: 123
Output: 321 - Example 2:
Input: -123
Output: -321 - Example 3:
Input: 120
Output: 21 - Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题目翻译
反转整数中的数字。
例子1:给定x=123,返回321;例子2:给定x=-123,返回-321。
本题的几个坑:
- 原整数是以0结尾的,该如何处理?——比如x=10或x=100,那么都返回1。
- 原整数反转后溢出怎么办?——比如x=1000000003,反转溢出,那么规定溢出的结果都返回0。
代码实现
利用python字符串的切片进行字符串反转。
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x<0:# 判断输入的输入数值是否为负数
y=-1*int(str(-x)[::-1]) # 如果为负数,将负数转换成正数进行字符串逆序,然后再添加负号
else:
y=int(str(x)[::-1])# 正数直接进行字符串逆序
if x < -2**31 or x >= 2**31-1:# 反转后的整数溢出,则返回 0。
y=0
return y
总结
- 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31,2 ^31 − 1]。
- str[::-1]:反向切片
- 关于序列切片是重点也是难点,平时学习中要注意多多掌握。
- 序列切片的知识:https://blog.csdn.net/saltriver/article/details/52194906