Java Program To Write Your Own atoi()

23 Jun, 2022
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer.
Syntax:  
int atoi(const char strn)
Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent.
Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number. If no valid conversion takes place, then the function returns zero.
Now let’s understand various ways in which one can create there own atoi() function supported by various conditions:
Approach 1: Following is a simple implementation of conversion without considering any special case. 
Initialize the result as 0.
Start from the first character and update result for every character.
For every character update the answer as result = result * 10 + (s[i] – ‘0’)
Java
// A simple Java program for// implementation of atoiclass GFG {     // A simple atoi() function    static int myAtoi(String str)    {               // If str is NULL or str contains non-numeric        // characters then return 0 as the number is not        // valid        if (str == "" || str.matches("[a-zA-Z]+") || str.matches(".*[0-9].*")) {            return 0;        }        // Initialize result        int res = 0;         // Iterate through all characters        // of input string and update result        // take ASCII character of corresponding digit and        // subtract the code from '0' to get numerical        // value and multiply res by 10 to shuffle        // digits left to update running total        for (int i = 0; i < str.length(); ++i)            res = res * 10 + str.charAt(i) - '0';         // return result.        return res;    }     // Driver code    public static void main(String[] args)    {        String str = "8f9789";                        // Function call        int val = myAtoi(str);        System.out.println(val);    }} // This code is contributed by PrinciRaj1992
89789
Approach 2: This implementation handles the negative numbers. If the first character is ‘-‘ then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying sign with it. 
Java
// Java program for// implementation of atoiclass GFG {     // A simple atoi() function    static int myAtoi(char[] str)    {         // Initialize result        int res = 0;         // Initialize sign as positive        int sign = 1;         // Initialize index of first digit        int i = 0;         // If number is negative, then        // update sign        if (str[0] == '-') {            sign = -1;             // Also update index of first            // digit            i++;        }         // Iterate through all digits        // and update the result        for (; i < str.length; ++i)            res = res * 10 + str[i] - '0';         // Return result with sign        return sign * res;    }     // Driver code    public static void main(String[] args)    {        char[] str = "-123".toCharArray();               // Function call        int val = myAtoi(str);        System.out.println(val);    }} // This code is contributed by 29AjayKumar
-123
Approach 3: This implementation handles various type of errors. If str is NULL or str contains non-numeric characters then return 0 as the number is not valid. 
 -134
Approach 4: Four corner cases needs to be handled: 
Discards all leading whitespaces
Sign of the number
Overflow
Invalid input
To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches. 
Dry Run: 
Below is the implementation of the above approach: 
Java
// A simple Java program for// implementation of atoiclass GFG {    static int myAtoi(char[] str)    {        int sign = 1, base = 0, i = 0;         // if whitespaces then ignore.        while (str[i] == ' ')        {            i++;        }         // sign of number        if (str[i] == '-' || str[i] == '+')        {            sign = 1 - 2 * (str[i++] == '-' ? 1 : 0);        }         // checking for valid input        while (i < str.length               && str[i] >= '0'               && str[i] <= '9') {             // handling overflow test case            if (base > Integer.MAX_VALUE / 10                || (base == Integer.MAX_VALUE / 10                    && str[i] - '0' > 7))            {                if (sign == 1)                    return Integer.MAX_VALUE;                else                    return Integer.MIN_VALUE;            }            base = 10 * base + (str[i++] - '0');        }        return base * sign;    }     // Driver code    public static void main(String[] args)    {        char str[] = " -123".toCharArray();               // Function call        int val = myAtoi(str);        System.out.printf("%d ", val);    }} // This code is contributed by 29AjayKumar
 -123
Complexity Analysis for all the above Approaches: 
Time Complexity: O(n). Only one traversal of string is needed.
Space Complexity: O(1). As no extra space is required.
Recursive program for atoi().
Exercise: Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.
Please refer complete article on Write your own atoi() for more details!
devendrasalunke
Adobe
Amazon
Code Brew
Microsoft
Morgan Stanley
Payu
Java Programs
Strings
Morgan Stanley
Amazon
Microsoft
Payu
Adobe
Code Brew
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.