题目
- Reverse Integer
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123
Output: 321
Example 2:
Input: x = -123
Output: -321
Example 3:
Input: x = 120
Output: 21
Constraints:
-2^31 <= x <= 2^31 - 1
基本思路
今天的题目对我们python新手非常友好,我们有两种思路,一种是转成字符串,反转加序号,一种是用数学的方式取余,余数*10,再加上下一步的取余。
很清晰的思路,唯一的坑就是转换的结果可能超过32位的上下界,判断输出的结果做一下限制。
注:使用python的我们要时刻把头埋低,比如用C语言解这个题,就没有转换成字符串的流畅解法,然后也不能在最后比较是不是越界,因为python的伪int类型是无限精度的,而c语言等,声明了32位int就是32位,需要计算前就进行判断,不然结果根本出不来。我们屏住呼吸,把这个题悄悄刷掉。嘘!
转换成字符串→反转字符串→还原符号→如果溢出就输出0→没问题就输出结果
这个比较简单直接给代码了
class Solution:
def reverse(self, x: int) -> int:
# 转为字符串,并处理符号
s = str(abs(x))
# 反转字符串
res = int(s[::-1]) # 切片操作,见知识点
# 还原符号
if x < 0:
res = -res
# 检查是否溢出
if res > 2**31 - 1 or res < -2**31:
return 0
return res
这个结果多刷几次就会不一样,落点还是要在自己的算法是否足够优雅清晰
思路二
这个题当然也可以用res*10+x%10这种数学的方式去结题,而不用借助强制类型转换,热心的勇者赶快来试试!这里贴一下别人的代码,也不卖关子了
class Solution:
def reverse(self, x: int) -> int:
res = 0
sign = -1 if x < 0 else 1
x = abs(x)
while(x > 0):
res = res * 10 + x % 10
x //= 10
if res > 2**31 - 1:
return 0
return res * sign
知识点
python的slice切片
python的这个sequence对象切片,也是python的核心特性之一,这里只是蜻蜓点水的列了一些,更多的用法,还要在代码实践中多多体会才行。
基本语法
sequence[start:end:step]
参数说明
# start: 起始索引(包含)
# end: 结束索引(不包含)
# step: 步长,可正可负
基础用法
s = "Hello World"
# 基本切片
print(s[0:5]) # "Hello"
print(s[:5]) # "Hello" (省略start)
print(s[6:]) # "World" (省略end)
print(s[:]) # "Hello World" (复制整个序列)
# 使用负索引
print(s[-5:]) # "World"
print(s[:-6]) # "Hello"
# 使用step
print(s[::2]) # "HloWrd" (每隔一个字符)
print(s[::-1]) # "dlroW olleH" (反转)
进阶理解
对于字符串s=“Hello World”
字符 | H | e | l | l | o | (空格) | W | o | r | l | d |
---|---|---|---|---|---|---|---|---|---|---|---|
正向索引 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
负向索引 | -11 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
一些奇怪的切片示例,这里的示例没有上下文,也不具备明显的逻辑动机,看起来不直观很正常,记住这里的::2
, ::-1
就行。可以用来生成奇偶序列或者反转。
切片表达式 | 结果 | 说明 |
---|---|---|
s[0:5] | “Hello” | 从索引0到4(不包含5) |
s[-5:] | “World” | 从倒数第5个到结束 |
s[:5] | “Hello” | 从开始到索引4 |
s[6:] | “World” | 从索引6到结束 |
s[::2] | “HloWrd” | 每隔一个字符取一个 |
s[::-1] | “dlroW olleH” | 反转整个字符串 |
s[-5:-2] | “Wor” | 从倒数第5个到倒数第3个 |