leetcode.0007. Reverse Integer
题目
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: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
参考答案(python3):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y = 0
if x > 0:
sgn = 1
else:
sgn = -1
x *= sgn
while x >= 1: # x=+(-)0 ,y=0
y = 10*y + x%10 # 重点,
x //= 10; # //= 取整赋值运算
y *= sgn
if (y < -2**31 or y > (2**31)-1 ):# 超出范围 ,返回0
return 0
return y
更优答案(python3):
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
neg = x < 0
num = str(abs(x))
reversed_num = num[::-1] # 字符串到序, 不用借助列表list.reverse()
if neg:
neg_reversed = int("-" + reversed_num)# 直接字符串, 转整数 int()
else:
neg_reversed = int(reversed_num)
if neg_reversed > (2**31 - 1) or neg_reversed < (-2**31): # 超出范围 ,返回0
neg_reversed = 0
return neg_reversed