Parse Integer Algorithm

The Parse Integer Algorithm is a widely used computing technique that is designed to convert a given input string of numeric characters into its corresponding integer representation. This algorithm is particularly useful for cases where the input data is received in the form of a string, but the required processing necessitates the use of integer data types. The algorithm scans the input string from left to right, identifying and processing each numeric character while simultaneously constructing the corresponding integer value. In addition to handling positive numbers, the Parse Integer Algorithm is also capable of managing negative numbers by detecting a preceding negative sign (-) in the input string. One common approach to implementing the Parse Integer Algorithm is through the iterative multiplication method. This involves initializing a variable to store the integer result, and setting its initial value to zero. The algorithm then iterates through each numeric character in the input string, converting the character to its corresponding integer value (e.g., '5' to 5) by subtracting the character code for '0'. The algorithm then multiplies the current integer result by 10 and adds the converted integer value of the current character. This process is repeated for each numeric character in the input string, ultimately yielding the final integer result. If the input string contains a negative sign, the final result is multiplied by -1 to obtain the correct negative integer representation. By following this approach, the Parse Integer Algorithm efficiently and accurately converts input strings of numeric characters into their integer equivalents, providing a robust solution for numerous computational use cases.
package Maths;

public class ParseInteger {
    public static void main(String[] args) {
        assert parseInt("123") == Integer.parseInt("123");
        assert parseInt("-123") == Integer.parseInt("-123");
        assert parseInt("0123") == Integer.parseInt("0123");
        assert parseInt("+123") == Integer.parseInt("+123");
    }

    /**
     * Parse a string to integer
     *
     * @param s the string
     * @return the integer value represented by the argument in decimal.
     * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
     */
    public static int parseInt(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        boolean isNegative = s.charAt(0) == '-';
        boolean isPositive = s.charAt(0) == '+';
        int number = 0;
        for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
            if (!Character.isDigit(s.charAt(i))) {
                throw new NumberFormatException("s=" + s);
            }
            number = number * 10 + s.charAt(i) - '0';
        }
        return isNegative ? -number : number;
    }
}

LANGUAGE:

DARK MODE: