LeetCode第 7 题:整数反转(C++)

7. 整数反转 - 力扣(LeetCode)

简单题,处理好溢出就行:

class Solution {
public:
    int reverse(int x) {
        long int res = 0;
        while(x){
            res = 10*res + x % 10;
            x = x/10;
        }
        if(res > 2147483647 || res < -2147483648)   return 0;
        return res;
    }
};

如果不用long:

class Solution {
public:
    int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > INT_MAX/10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
            if (rev < INT_MIN/10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
};

你可能感兴趣的:(leetcode)