一、题目描述
https://leetcode.com/problems/reverse-integer/description/
题目原文:
Given a 32-bit signed integer, reverse digits of an integer.(给定一个32位有符号整数,求它的倒数。)
Example 1:
Input: 123 Output: 321Example 2:
Input: -123 Output: -321Example 3:
Input: 120 Output: 21Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.(假设我们正在处理一个只能在32位有符号整数范围内存储整数的环境。为了解决这个问题,假设当反整数溢出时,函数返回0。)
二、题目分析
将int数值转成字符串,对字符串进行翻转,再转回int数值返回。
注意:
1.int数值有正负之分,需要考虑符号。
2.返回反整数时需要考虑溢出,溢出时返回0。
三、代码实现
class Solution(object): def reverse(self, x): """ :type x: int :rtype: int """ if x>0: x=int(str(abs(x))[::-1]) return x if x < 2147483648 else 0 elif x<0: x=-int(str(abs(x))[::-1]) return x if x >= -2147483648 else 0 else: return 0