Solution in Java


  • 0
    A
    import java.lang.Math.*;
    class Solution {
        public int reverse(int x) {
            boolean negate = false;
            if (x < 0){
                negate = true;
            }
            int n = Math.abs(x);
            int d;
            int rnum = 0;
            try {
                while(n > 0) {
                    d = n % 10;
                    rnum = Math.addExact(Math.multiplyExact(rnum,10), d);
                    n = n/10;
                }       
            }
            catch(ArithmeticException e){
                return 0;
            }
            if (negate){
                return Math.toIntExact(-1*rnum);
            }
            return Math.toIntExact(rnum);    
        }
    }
    

Log in to reply
 

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