您的位置:首页 > 编程语言 > Python开发

LeetCode--Reverse Integer(整数反转)Python

2017-12-05 15:41 543 查看
题目:

给定一个整数,返回反转后的整数。如给定12,返回21,给定210返回12,给定-231返回-132.

解题思路:

将整数先转为字符串格式。再倒序对字符串进行读取。

代码(Python):

class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
# if x<-2^31 or x>2^31-1:
# return 0
count = 0
s = str(x)
if s[0]=='-':
for i in range(len(s)-1):
count = count*10+int(s[-1-i])
if count>2**31:
return 0
return -count
else:
for i in range(len(s)):
count = count*10+int(s[-i-1])
if count>2**31-1:
return 0
return count
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: