My accepted solution for Java 8


  • 0
    S

    Not sure how much overhead the try/catch adds, but this code is quite, readable and works.

    public int reverse(int x) {
            int inverted = 0;
            int buffer = Math.abs(x);
            try {
                while(buffer > 0) {
                    int ones = buffer % 10;
    
                    inverted = Math.addExact(Math.multiplyExact(inverted, 10), ones);
    
                    buffer = buffer / 10;
                }
    
                return (x > 0) ? inverted : inverted * -1;
            } catch (ArithmeticException e) {
                return 0;
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.