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

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

Idea – 1

We would remember the sign and then work with the absolute value. Need to be careful, absolute value can be too large for an integer. And during the reversing for each next digit we would check if it will cause an overflow or an underflow. The time complexity is O(\lg{n}) and space is O(1).

class Solution {
    
    private static final int TENTH = Integer.MAX_VALUE/10;
    
    public int reverse(int x) {
        if(x==Integer.MIN_VALUE)
        {
            return 0;
        }
        
        boolean negative = x < 0;
        x = Math.abs(x);
        
        int y = 0;
        while(x > 0)
        {
            int d = x%10;
            if(toobig(y, d, negative))
            {
                return 0;
            }
            
            y = 10*y + d;
            
            x /= 10;
        }
        
        return negative ? -y : y;
    }
    
    private boolean toobig(int y, int d, boolean negative)
    {
        if(y < TENTH)
        {
            return false;
        }
        else if(y > TENTH)
        {
            return true;
        }
        else
        {
            return (negative && d == 9) || (!negative && d > 7);
        }
    }
}


Runtime: 1 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 32.5 MB, less than 100.00% of Java online submissions for Reverse Integer.

Leave a comment