LeetCode-7:Reverse Integer(翻转整数)

题目:

Given a 32-bit signed integer, reverse digits of an integer.

例子:

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

问题解析:

给定一个 32 位有符号整数,将整数中的数字进行反转。

思路标签

溢出边界

解答:

1.余数除数

  • 简单的利用余数和除数即可实现。
  • 需要注意溢出情况:
  • 因为我们利用的是:temp = rev*10 + pop,(这里rev表示翻转数字,pop表示x/10后的余数),所以如果temp = rev*10 + pop最后导致溢出,那么一定就有rev>=INT_MAX/10;
  • 如果rev>=INT_MAX/10,那么temp = rev*10 + pop一定就会溢出;
  • 如果rev==INT_MAX/10,那么只要pop>7,那么temp = rev*10 + pop一定就会溢出;
  • 上面是正数的情况,负数的情况类似。
class Solution {
public:
    int reverse(int x) {
        int reverseInt = 0;
        while(x != 0){
            int digit = x % 10;
            x /= 10;
            if (reverseInt > INT_MAX/10 || (reverseInt == INT_MAX/10 && digit > 7))
                return 0;
            if (reverseInt < INT_MIN/10 || (reverseInt == INT_MIN/10 && digit < -8))
                return 0;

            reverseInt = reverseInt*10 + digit;
        }

        return reverseInt;
    }
};
点赞