String to Integer in Java 8 without custom overflow checking


  • 0
    P

    The basic logic behind this kind of solution is that a = a * 10 + d can be used to append the digit d to a, assuming their signs are compatible. 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 Integer.MIN_VALUE or Integer.MAX_VALUE as required by the problem.

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

    class Solution {
        public int myAtoi(String str) {
            str = str.trim();
            boolean negative = str.startsWith("-");
            if (str.startsWith("-") || str.startsWith("+")) {
                str = str.substring(1);
            }
            try {
                int ret = 0;
                for (char c: str.toCharArray()) {
                    int d = c - '0';
                    if (d < 0 || d > 9) { // or, if allowed: if (!Character.isDigit(c))
                        break;
                    }
                    ret = Math.addExact(Math.multiplyExact(ret, 10), d);
                }
                if (negative) {
                  ret = Math.multiplyExact(ret, -1);
                }
                return ret;
            } catch (ArithmeticException e) {
                return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
        }
    }
    

    Space complexity: O(1) (the size of a few ints)
    Time complexity: O(n) in the length of the String.


Log in to reply
 

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