Problem Description:
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, then return 0
.
题目要求反转整数中的数字。
思路一:
首先判断原数字的正负,用flag记录一下。通过循环对10取余得到尾部数字,一步步乘10构造新的翻转后的整数。最后判断结果是否溢出,若溢出则输出0.
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
flag = 1
else:
flag = -1
x = abs(x)
x_new = 0
while(x):
x_new = 10 * x_new + x % 10
x = x // 10
x_new = flag * x_new
return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0
结果如下。
思路二:
利用Python的字符串切片 step=-1 操作来实现对整数的反转,反转后的字符串转换为整数后输出。
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
flag = 1
else:
flag = -1
x = abs(x)
x_new = str(x)
x_new = int(x_new[::-1])
x_new = flag * x_new
return x_new if x_new < 2147483648 and x_new >= -2147483648 else 0
结果如下:
关于python切片的知识:
python切片对象的索引分为正索引和负索引两部分
完整的切片表达式包含两个 “ : ”,用于分隔三个参数 ( start_index、end_index、step )。当只有一个 “ : ” 时,默认第三个参数step=1;当一个 “ : ” 也没有时,start_index=end_index,表示切取start_index指定的那个元素。