Leetcode 7:整数反转(超详细的解法!!!)

版权声明:本文为博主原创文章,未经博主允许不得转载。有事联系:[email protected] https://blog.csdn.net/qq_17550379/article/details/84666773

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

示例 1:

输入: 123
输出: 321

示例 2:

输入: -123
输出: -321

示例 3:

输入: 120
输出: 21

注意:

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

解题思路

这个问题非常简单,我们直接按照题目意思操作即可。

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        pos_x = abs(x)
        str_pos_x = str(pos_x)[::-1]
        res = int(str_pos_x)
        if res > pow(2, 31):
            res = 0
        return -res if x < 0 else res

上面的这种做法我们完全是通过python的特性实现的。而我们如果要使用其它编程语言的话,可以这样操作

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        neg = 1 if x >= 0 else -1
        x *= neg
        num = 0
        while x:
            num = num*10 + x%10
            x //= 10
        if num > (2**31) - 1 or num < -1*(2**31):
            return 0
        return num*neg

我将该问题的其他语言版本添加到了我的GitHub Leetcode

如有问题,希望大家指出!!!

猜你喜欢

转载自blog.csdn.net/qq_17550379/article/details/84666773