Inverted integer LeetCode 7. Reverse Integer

Inverted integer LeetCode 7. Reverse Integer

7. 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
Direct reversal

Note that the overflow problem shaping. I used here is greater than the resultant value MAX / 10 is determined. Of course also possible to use double-determination of the sign bit overflow. Also possible to use multiplied by 10 and divided by 10, the method of comparing two numbers is determined to overflow. Or use exceptions to catch the overflow can. The time complexity is O (n), the spatial complexity is O (1)

 public int reverse(int x) {
        if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE){
            return 0;
        }
        int s = Integer.MAX_VALUE;
        int sign = 1;
        if( x < 0){
            sign = -1;
        }
        int y = Math.abs(x);
        int res = 0;

        while(y != 0){          
            if(res > Integer.MAX_VALUE/10){
                return 0;
            }
            res = res* 10 + (y % 10);
            y = y/10;
        }
        
        return res * sign;   
    }
Published 36 original articles · won praise 8 · views 30000 +

Guess you like

Origin blog.csdn.net/qq_32763643/article/details/104072633