LeetCode 腾讯精选练习50 题——7. 整数反转

一、题目

LeetCode 腾讯精选练习50 题——7. 整数反转

二、解法

一开始是打算这么写的......没想到还有ans = ans*10 + x %10这样简单的性质。

还有判断溢出(2^31=2147483648)时发现标准答案的很直接:LeetCode 腾讯精选练习50 题——7. 整数反转

class Solution {
public:
    int reverse(int x) {
        int temp = x;
        int bit = 0;
        vector<int> num;
        while(temp != 0) {
            num.push_back(temp%10);
            temp = temp / 10;
            bit++;
        }
        long long int ans = 0;
        for(int i = 0; i < bit; i++)
            ans += num[i] * pow(10, bit-i-1);
        if(ans < -pow(2,31) || ans > pow(2,31)-1)
            return 0;
        return ans;
    }
};

官方提供的解答:

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