Write your own atoi()

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.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
  
int main()
{
    int val;
    char strn1[] = "12546";
  
    val = atoi(strn1);
    printf("String value = %s\n", strn1);
    printf("Integer value = %d\n", val);
  
    char strn2[] = "GeeksforGeeks";
    val = atoi(strn2);
    printf("String value = %s\n", strn2);
    printf("Integer value = %d\n", val);
  
    return (0);
}

chevron_right


Output:

String value = 12546
Integer value = 12546
String value = GeeksforGeeks
Integer value = 0

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’)

C

filter_none

edit
close

play_arrow

link
brightness_4
code

// Program to implement atoi() in C
#include <stdio.h>
  
// A simple atoi() function
int myAtoi(char* str)
{
    // Initialize result
    int res = 0;
  
    // Iterate through all characters
    // of input string and update result
    for (int i = 0; str[i]
                    != '\0';
         ++i)
        res = res * 10 + str[i] - '0';
  
    // return result.
    return res;
}
  
// Driver program to test above function
int main()
{
    char str[] = "89789";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}

chevron_right


C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C++ program for
// implementation of atoi
#include <bits/stdc++.h>
using namespace std;
  
// A simple atoi() function
int myAtoi(char* str)
{
    // Initialize result
    int res = 0;
  
    // Iterate through all characters
    // of input string and update result
    for (int i = 0; str[i]
                    != '\0';
         ++i)
        res = res * 10 + str[i] - '0';
  
    // return result.
    return res;
}
  
// Driver code
int main()
{
    char str[] = "89789";
    int val = myAtoi(str);
    cout << val;
    return 0;
}
  
// This is code is contributed by rathbhupendra

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple Java program for
// implementation of atoi
class GFG {
  
    // A simple atoi() function
    static int myAtoi(String str)
    {
        // Initialize result
        int res = 0;
  
        // Iterate through all characters of
        // input string and update result
        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 = "89789";
        int val = myAtoi(str);
        System.out.println(val);
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for implementation of atoi
  
# A simple atoi() function
def myAtoi(string):
    res = 0
  
    # Iterate through all characters of input string and 
    # update result
    for i in xrange(len(string)):
        res = res * 10 + (ord(string[i]) - ord('0'))
  
    return res
  
# Driver program
string = "89789"
print myAtoi(string)
  
# This code is contributed by BHAVYA JAIN

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C# program for implementation
// of atoi
using System;
  
class GFG {
  
    // A simple atoi() function
    static int myAtoi(string str)
    {
        int res = 0; // Initialize result
  
        // Iterate through all characters of
        // input string and update result
        for (int i = 0; i < str.Length; ++i)
            res = res * 10 + str[i] - '0';
  
        // return result.
        return res;
    }
  
    // Driver program to test above function
    public static void Main()
    {
        string str = "89789";
        int val = myAtoi(str);
        Console.Write(val);
    }
}
  
// This code is contributed by Sam007.

chevron_right



Output:

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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C++ program for
// implementation of atoi
#include <bits/stdc++.h>
using namespace std;
  
// A simple atoi() function
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 (; str[i] != '\0'; ++i)
        res = res * 10 + str[i] - '0';
  
    // Return result with sign
    return sign * res;
}
  
// Driver code
int main()
{
    char str[] = "-123";
    int val = myAtoi(str);
    cout << val;
    return 0;
}
  
// This is code is contributed by rathbhupendra

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

// A C program for
// implementation of atoi
#include <stdio.h>
  
// A simple atoi() function
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 (; str[i] != '\0'; ++i)
        res = res * 10 + str[i] - '0';
  
    // Return result with sign
    return sign * res;
}
  
// Driver program to test above function
int main()
{
    char str[] = "-123";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for
// implementation of atoi
class 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();
        int val = myAtoi(str);
        System.out.println(val);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for implementation of atoi
  
# A simple atoi() function
def myAtoi(string):
    res = 0
    # initialize sign as positive
    sign = 1
    i = 0
  
    # if number is negative then update sign
    if string[0] == '-':
        sign = -1
        i+= 1
  
    # Iterate through all characters of input string and update result
    for j in xrange(i, len(string)):
        res = res * 10 + (ord(string[j]) - ord('0'))
  
    return sign * res
  
# Driver program
string = "-123"
print myAtoi(string)
  
# This code is contributed by BHAVYA JAIN

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for implementation of atoi
using System;
  
class GFG {
  
    // A simple atoi() function
    static int myAtoi(string 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 program to test above function
    public static void Main()
    {
        string str = "-123";
        int val = myAtoi(str);
        Console.Write(val);
    }
}
  
// This code is contributed by Sam007.

chevron_right



Output:

-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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C++ program for
// implementation of atoi
  
#include <stdio.h>
  
// A utility function to check
// whether x is numeric
bool isNumericChar(char x)
{
    return (x >= '0' && x <= '9')
               ? true
               : false;
}
  
// A simple atoi() function.
// If the given string contains
// any invalid character, then
// this function returns 0
int myAtoi(char* str)
{
    if (*str == '\0')
        return 0;
  
    // 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 of
    // input string and update result
    for (; str[i] != '\0'; ++i) {
  
        // You may add some lines
        // to write error message
        if (isNumericChar(str[i]) == false)
            return 0;
  
        // to error stream
        res = res * 10 + str[i] - '0';
    }
  
    // Return result with sign
    return sign * res;
}
  
// Driver program to test above function
int main()
{
    char str[] = "-134";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple Java program for
// implementation of atoi
class Atoi {
  
    // A simple atoi() function.
    // If the given string contains
    // any invalid character, then
    // this function returns 0
    public static int atoi(String str)
    {
  
        if (str.length() == 0) {
            return -1;
        }
        // Initialize sign as positive
        int sign = 1;
  
        // Initialize result
        int res = 0;
  
        // Initialize index of first digit
        int i = 0;
  
        // If number is negative,
        // then update sign
        if (str.charAt(i) == '-') {
            sign = -1;
  
            // Also update index of first digit
            i++;
        }
  
        // Iterate through all digits of input
        // string and update result
        for (; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i)) == false) {
                return -1;
            }
            res = res * 10
                  + Character.getNumericValue(
                        str.charAt(i));
        }
  
        return sign * res;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "-134";
        int num = atoi(str);
        System.out.println(num);
    }
}
  
// This code is contributed by Anonymous_Geek

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program for implementation of atoi
  
# A utility function to check whether x is numeric
def isNumericChar(x):
    if (x >= '0' and x <= '9'):
        return True
    return False
  
# A simple atoi() function. If the given string contains
# any invalid character, then this function returns 0
def myAtoi(string):
    if len(string) == 0:
        return 0
  
    res = 0
    # initialize sign as positive
    sign = 1
    i = 0
  
    # if number is negative then update sign
    if string[0] == '-':
        sign = -1
        i+= 1
  
    # Iterate through all characters of input string and update result
    for j in xrange(i, len(string)):
        # You may add some lines to write error message to error stream
        if isNumericChar(string[j] == False):
            return 0
  
        res = res * 10 + (ord(string[j]) - ord('0'))
  
    return sign * res
  
# Driver program
string = "-134"
print myAtoi(string)
  
# This code is contributed by BHAVYA JAIN

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C# program for implementation of atoi
using System;
  
class Atoi {
  
    // A simple atoi() function. If the given string contains
    // any invalid character, then this function returns 0
    public static int atoi(String str)
    {
  
        if (str.Length == 0) {
            return -1;
        }
        int sign = 1; // Initialize sign as positive
        int res = 0; // Initialize result
        int i = 0; // Initialize index of first digit
  
        // If number is negative, then update sign
        if (str[i] == '-') {
            sign = -1;
            i++; // Also update index of first digit
        }
  
        // Iterate through all digits of input
        // string and update result
        for (; i < str.Length; i++) {
            if (char.IsDigit(str[i]) == false) {
                return -1;
            }
            res = res * 10 + int.Parse(str[i].ToString());
        }
  
        return sign * res;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        String str = "-134";
        int num = atoi(str);
        Console.WriteLine(num);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C++ program for
// implementation of atoi
#include <bits/stdc++.h>
  
using namespace std;
int myAtoi(const 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++] == '-');
    }
    // checking for valid input
    while (str[i] >= '0' && str[i] <= '9') {
        // handling overflow test case
        if (base > INT_MAX / 10
            || (base == INT_MAX / 10
                && str[i] - '0' > 7)) {
            if (sign == 1)
                return INT_MAX;
            else
                return INT_MIN;
        }
        base = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
  
int main()
{
    char str[] = "  -123";
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}
// This code is contributed by Yogesh shukla.

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple Java program for
// implementation of atoi
class 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();
        int val = myAtoi(str);
        System.out.printf("%d ", val);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A simple C# program for implementation of atoi
using System;
  
class 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 > int.MaxValue / 10 || (Base == int.MaxValue / 10 && str[i] - '0' > 7)) {
                if (sign == 1)
                    return int.MaxValue;
                else
                    return int.MinValue;
            }
            Base = 10 * Base + (str[i++] - '0');
        }
        return Base * sign;
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        char[] str = " -123".ToCharArray();
        int val = myAtoi(str);
        Console.Write("{0} ", val);
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output :

-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.

This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up