7. 整数反转

https://leetcode-cn.com/problems/reverse-integer/

解法一:

初始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;
    }
};

解法二:py字符处理

先转str,然后倒置,再转int即可,注意负数特殊。

因为python的整数类型范围似乎比c语言要大,因此不用上面的做法判断溢出,直接检验是否在[-2^31, 2^31-1]即可

class Solution:
    def reverse(self, x: int) -> int:        
        if x >= 0:
            res = int(str(x)[::-1])
        else:    #负数
            res = -int(str(x)[1:][::-1])
        if res < -2**31 or res > 2**31-1:
            return 0
        return res

最后更新于