2

【leetcode】7.整数反转

 2 years ago
source link: https://blog.feelyou.top/posts/leetcode7.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【leetcode】7.整数反转

2018-12-05

5

给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [−231231, 231231, − 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。


python

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
x = list(str(x))
if x[0] == '-':
x = (-1)*int(''.join(x[-1:-len(x):-1]))
else:
x = int(''.join(x[::-1]))
if x>= (-1)*(2**31) and x<=2**31:
return x
else:
return 0

参考资料:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK