Java solution


  • 0
    K

    My solution:

    class Solution {
        public int reverse(int x) {
            if(x == Integer.MIN_VALUE) {
                return 0;
            }
            List<Integer> holder = new ArrayList<>();
            int order = 10;
            int sign = x > 0 ? 1 : -1;
            if (x < 0) x = -x;
            double pow = 1;
            do {
                int residual = x % order;
                if (residual != 0 || !holder.isEmpty()) {
                    holder.add(residual);
                    pow *= order;
                }
                x = x / order;
            }
            while (x != 0);
            
            pow /= order;
            
            if (holder.isEmpty())
                return 0;
            
            double temp = 0;
            for (Integer val : holder) {
                temp += (double) val * pow;
                if (temp > Integer.MAX_VALUE) {
                    return 0;
                }
                pow /= order;
            }
            
            return sign * (int) temp;
        }
    }
    

Log in to reply
 

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