Solution in Java 8 without Strings, longs or custom overflow checking


  • 0
    P

    The basic logic behind this kind of solution is that x % 10 retrieves the last digit of x (giving the result the same sign as x) and that x /= 10 removes x's last digit. Neither of these operations can overflow.

    At the same time, a = a * 10 + d can be used to append the digit d to a, assuming that a and d have the same sign OR that either is 0. Both the multiplication and the addition here can result in overflow, however, which can be very difficult to efficiently check for.
    Luckily, Java 8 adds methods to the java.lang.Math class that implement this checking for us and throw ArithmeticException if overflow occurs! This exception can then be caught and used to return 0 as required by the problem.

    Taking all of the above into consideration, the solution is trivial:

    class Solution {
        public int reverse(int x) {
            int ret = 0;
            while (x != 0) {
                int d = x % 10;
                try {
                    ret = Math.addExact(Math.multiplyExact(ret, 10), d);  
                } catch (ArithmeticException e) {
                    return 0;
                }
                x /= 10;
            }
            return ret;
        }
    }
    

    Space complexity: O(1).
    Time complexity: O(n) in the number of digits.


Log in to reply
 

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