7. Reverse Integer

https://leetcode.com/problems/reverse-integer/description/
题目大意:给一个整数,返回其每位倒序的整数。
解题思路:初始old = 0,每次取整数n的最低位tail,然后从低向高构建新整数new = old * 10 + tail。取得tail后,去掉n的最低位,n=n/10,进入下一轮,直到n=0。
注意为了避免溢出,每次记录old和new,然后用相反的方法:old = (new-tail)/ 10,判断old和new是否相等,若前后不相等,说明溢出。

代码:

class Solution {
public:
    int reverse(int x) {
        int result = 0;
        while (x != 0) {
            int tail = x % 10;
            int newResult = result * 10 + tail;
            if ((newResult - tail) / 10 != result) return 0;
            x /= 10;
            result = newResult;
        }
        return result;
    }
};

python实现:基本上与c语言相同,不同在于负数取模和除法需要特别处理,在此简化为先用正数处理,再转为负数。此外还需注意判断是否溢出,因为python的整数类型范围似乎比c语言要大,因此不用上面的做法判断溢出,直接检验是否在[-2^31, 2^31-1]即可

class Solution:
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        result = 0
        while x != 0:
            if x > 0:  
                tail = x % 10
            else:
                tail = -(-x % 10)   #考虑负数处理         
            newResult = result * 10 + tail          
            if x > 0:
                x //= 10
            else:
                x = -(-x // 10)  #考虑负数处理
            result = newResult

        if result < 2**31-1 and result > -2**31:
            return result
        else:
            return 0

猜你喜欢

转载自blog.csdn.net/u012033124/article/details/79860087