LeetCode刷题 7 整数反转

题目

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

输入:123
输出:321
示例2
输出:-123
输出:-321
注意
假设我们的环境只能存储得下 32 位的有符号整数,则其数值范围为 [-(2^31), 2^31 - 1]。请根据这个假设,如果反转后整数溢出那么就返回 0。

思考

还是最简单的用数学方法加循环,取模和除法。

解题思路

首先,循环倒序求出每一位数字。然后叠加到最后结果上,最后需要判断不要超出32位的有符号整数的表示范围。

Python实现

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """    
        tempX = x
        bNegative = False
        intMax = (pow(2, 31) - 1)
        intMin = -(pow(2, 31))
        
        if(tempX < 0):
            tempX = abs(tempX)
            bNegative = True
            
        res = 0
        while(tempX != 0):
            num = tempX % 10
            tempX = int(tempX / 10)
            res = res * 10 + num
            if(res >= intMax):
                return 0
            elif(res <= intMin):
                return 0
            
        if(bNegative):
            res *= -1
            
        return res

在LeetCode上跑了68ms

C++实现

#include 
class Solution 
{
public:
    int reverse(int x) 
    {
        int num = 0;
        int tempX = x;
        int res = 0;
        int intMax = pow(2, 31) - 1;
        int intMin = -(pow(2, 31));
        
        while(tempX != 0)
        {
            num = tempX % 10;
            tempX = int(tempX / 10);
            // intMax = 2147483647
            if((res > intMax / 10) || ((res == intMax / 10) && (num > 7)))
            {
                return 0;
            }
            // intMin = -2147483648
            if((res < intMin / 10) || ((res == intMin / 10) && (num < -8)))
            {
                return 0;
            }
             res = res * 10 + num;
        }
        return res;
    }
};

在LeetCode上跑了20ms

你可能感兴趣的:(leetcode,c++,python)