JAVA-LeetCode simple 07

1. Title

Given a 32-bit signed integer, you need to invert the digits on each of the integers.
Example 1:

Input: 123
Output: 321
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.

Source: LeetCode

Link: Inverted integer

2. Analysis

Reversing an integer is equivalent to pushing it bit by bit and then bit by bit. For
example,
the order of 123->12->1 is first 3, then 2, and last 1, and
the order of pushing is first 3, then 2, Finally 1,
get 3 first and save it, then get 2, 3 needs to carry 3 10, then push in 2, get 32,
finally get 1, 32 needs to carry
10, get 320, push in 1. Get 321
this code The key lies in the judgment of the value range and the position of the judgment. It cannot be placed at the end, which will cause the maximum or minimum value to be exceeded.

3. Code example

public static int reverse(int a){
    
    
        int b = 0;
        int num = 0;
        while(a !=0){
    
    
            b=a%10;
            a/=10;
            if (num>Integer.MAX_VALUE/10 ||(b==Integer.MAX_VALUE/10 && b>7)) return 0;
            if (num>Integer.MAX_VALUE/10 ||(b==Integer.MAX_VALUE/10 && b<-8)) return 0;
            num=num*10+b;
        }

        return num;
    }

Guess you like

Origin blog.csdn.net/weixin_44712669/article/details/111500230