LeetCode 7. Reverse Integer (Medium)

题目

&npsb;
Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Constraints:
-231 <= x <= 231 - 1

 

思路

解法 (Java):

关键点在于考虑数字反转之后是否超过Integer的最大最小值边界。

由于

Integer.MAX_VALUE=2147483647

Integer.MIN_VALUE=-2147483648

因为x的值在最大值和最小值之间,所以x如果是10位数字,反转后的值的最后一位要么是1,要么是2

Math.abs(res) = Integer.MAX_VALUE / 10 时,如果res还有下一位要添加,必然是1或2添加在res末位,

res为正数,Integer.MAX_VALUE 的末位是7res必然小于整数最大值。

res为负数,Integer.MIN_VALUE的末位是8res必然大于整数最小值。

把正负两种情况结合起来,即 Math.abs(res) > Integer.MAX_VALUE / 10 时,为溢出情况,其他情况则在整数表示区间内。

class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (Math.abs(res) > Integer.MAX_VALUE / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
}
posted @ 2021-12-30 00:54  红鲤鱼绿鲤鱼与阿米娅  阅读(25)  评论(0)    收藏  举报