LeetCode Question Bank #7 Integer Reversal (Java)

Title description:
Given a 32-bit signed integer, you need to reverse the digits on each of the integers.

示例 1:

输入: 123
输出: 321
 示例 2:

输入: -123
输出: -321
示例 3:

输入: 120
输出: 21

Note:
Assuming that our environment can only store 32-bit signed integers, the value range is [−231,231 − 1]. According to this assumption, if the integer overflows after the inversion, it returns 0.

The focus of this question is to calculate two overflow conditions:
first: n is greater than 7 when a is greater than MAX_VALUE/10 or a is equal to MAX_VALUE/10 (2 to the 31st power-the last digit is 7)
second: a is less than MIN_VALUE When /10 or a is equal to MIN_VALUE/10, n is greater than -8 (the last digit of -2 to the 31st power is 8)

class Solution {
    
    
    public int reverse(int x) {
    
    
        int a=0;
        while(x!=0){
    
    
            int n=x%10;
            //计算两个溢出条件;
            //第一:a大于MAX_VALUE/10或者a等于MAX_VALUE/10时n大于7(2的31次方-1最后一位为7)
            //第二:a小于MIN_VALUE/10或者a等于MIN_VALUE/10时n大于-8(-2的31次方最后一位为8)
            if(a > Integer.MAX_VALUE / 10 || (a == Integer.MAX_VALUE / 10 && n > 7)){
    
    
                return 0;
            }
            if(a < Integer.MIN_VALUE / 10 || (a == Integer.MIN_VALUE / 10 && n < -8)){
    
    
                return 0;
            }
            a=a*10+n;
            x/=10;
        }
        return a;
    }
}

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/111825691