问题
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
"""
negative = x < 0
if negative:
x = 0 - x
if x % 10 == 0:
x = x // 10
l = []
while x:
l.append(x % 10)
x = x // 10
number = 0
count = 0
for i in l[::-1]:
number += (10**count) * i
count += 1
if negative:
return 0 - number
else:
return number
结果给我报错了
error_picture
后来突然反应过来,原来将它倒过来之后,也是可能会溢出的,于是改之
Solution
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
negative = x < 0
if negative:
x = 0 - x
if x % 10 == 0:
x = x // 10
l = []
while x:
l.append(x % 10)
x = x // 10
number = 0
count = 0
for i in l[::-1]:
number += (10**count) * i
count += 1
if number > 2**31 - 1:
return 0
else:
if negative:
return 0 - number
else:
return number
网友评论