[LeetCode-Java Exercise] 07. Integer Reversal (Simple)

1. Title description

Insert picture description here

2. Problem solving ideas

We can construct one digit of the inverted integer at a time. In doing so, we can check in advance whether appending another digit to the original integer will cause overflow.
The main difficulty of this question is to determine whether it overflows, so you can check in advance whether it will cause overflow.
For ease of explanation, we assume that rev is a positive number.
If temp = rev⋅10+pop causes overflow, then there must be rev≥ 10/INTMAX.
If rev>10/INTMAX, then temp =rev⋅10+pop must overflow.
If rev== 10/INTMAX, then as long as pop>7, temp =rev⋅10+pop will overflow.
Similar logic can be applied when rev is negative.

3. Code implementation

class Solution {
    
    
    public int reverse(int x) {
    
    
        int rev = 0;
        while (x != 0) {
    
    
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/113361280