题目
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 hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
自己的思路
变成字符串反转,再转数字
class Solution:
def reverse(self, x):"""
:type x: int
:rtype: int
"""
if -2**31 < x <2**31:
s = list(str(x))
if s[0] == '-':
t = s[1:]
t.reverse()
s[1:] = t
else:
s.reverse()
y = int(''.join(s))
if -2**31 < y <2**31:
return y
return 0
参考
法一
循环通过对10取模得到尾部数字,一步步乘10构造新的翻转后的整数即可
answer = 0
sign = 1 if x > 0 else -1
x = abs(x)
while x > 0:
answer = answer * 10 + x % 10
x //= 10
return answer
法二
if x < 0:
y = -1 * int(str(-x)[::-1])
else:
y = int(str(x)[::-1])
if y > 2**31 or y < -2**31:
y = 0
return y
知识点:
所有标准序列操作(索引,切片,乘法,资格检查,最值等)都适用于字符串,但字符串是不可变的,不能赋值
--------------新手刷题,仅用于自身记录,如有错误,欢迎指出---------------