欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Reverse Integer

程序员文章站 2024-03-22 14:04:22
...

Reverse Integer

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 store integers within the 32-bit signed integer range: [−2 ^ 31 ,2 ^ 31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Python代码:

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        str_x = str(abs(x))
        result = int(str_x[::-1])
        if x < 0 :
            result *= -1

        if (result > 2**31 or result < -(2**31-1)) :
            return 0

        return result

思路:

取绝对值 , 转化为字符串 , 逆序 , 再转化为数字 , 判断是否溢出

相关标签: Python