一、题目

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

 

相关文章:

  • 2021-04-07
  • 2021-11-21
  • 2021-11-25
  • 2021-05-08
  • 2021-04-30
  • 2021-10-14
  • 2021-05-28
  • 2021-04-19
猜你喜欢
  • 2022-12-23
  • 2021-05-02
  • 2021-12-17
  • 2021-09-29
  • 2021-06-17
  • 2021-12-01
  • 2021-08-31
相关资源
相似解决方案