问题描述
Reverse digits of an integer.
Example1: x = 123, return 321 Example2: x = -123, return -321
click to show spoilers.
Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Subscribe to see which companies asked this question.
将数字反转,注意如果反转后数字溢出(超出32位有符号数的范围),返回0
解决方法一
直观的方法,将数字转换为字符,将字符直接反转。负数时需进行“-”的处理。特殊情况为-9到9,不用反转;反转时如100后面为0的数字转变为001,但此处是数字,所以应打印1。 python进行字符转int时自动进行了处理。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | #!/usr/bin/env python
# *-*coding=utf-8*-*
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x >= 0:
x=str(x)[::-1] # :-1 反向遍历字符
if int(x) > 2147483648:
return 0
else:
return int(x)
else:
# 负数,增加"-"的处理
x=str(x)[::-1]
if int("-"+x[:-1]) < -2147483647:
return 0
else:
return int("-"+x[:-1])
if __name__ == "__main__":
a = Solution()
b = a.reverse(12345)
print(b)
|
运行结果: 54321 leetcode case测试结果:
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 52 ms
解决方法二:
321 321%10 取最后一位1 321/10 去掉倒数第二位,32%10 取最后一位2 32/10 去掉倒数第三位, 3%10 取最后一位3 直到为0 重新组成 1 110 +2 1210 +3 至少往下移动一位即*10
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #!/usr/bin/env python
# *-*coding=utf-8*-*
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
y=0
if -10 < x < 10:
return x
elif x >= 10:
while x != 0:
y = y * 10 + x%10
x /= 10
if y < 2147483648:
return y
else:
return 0
else:
x=abs(x)
while x != 0:
y = y * 10 + x%10
x /= 10
if -y > -2147483647:
return -y
else:
return 0
if __name__ == "__main__":
a = Solution()
b = a.reverse(-12345)
print(b)
|
运行结果 -54321
leetcode测试结果: 1032 / 1032 test cases passed. Status: Accepted Runtime: 46 ms 在提交的python语言的答案中,速度已接近最优结果。