跳转至

7.Reverse Integer

Tags: Easy Math

Links: https://leetcode.com/problems/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.


class Solution {
public:
    int reverse(int x) {
        int result = 0;

        while(x != 0){
            if (abs(result) > INT_MAX / 10) return 0;
            result = result * 10 + x % 10;
            x /= 10;
        }

        return result;
    }
};

可以不用 check 是否等于 214748364 ,因为输入的x也是一个整型数,所以x的范围也应该在 -2147483648~2147483647 之间,那么x的第一位只能是1或者2,翻转之后 res 的最后一位只能是1或2,所以 res 只能是 2147483641 或 2147483642 都在 int 的范围内。但是它们对应的x为 1463847412 和 2463847412,后者超出了数值范围。所以当过程中 res 等于 214748364 时, 输入的x只能为 1463847412, 翻转后的结果为 2147483641,都在正确的范围内,所以不用 check。