Open In App

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 of atoi()

int atoi(const char strn);

Parameters

Return Value

Example




#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int val;
    char strn1[] = "12546";
 
    val = atoi(strn1);
    cout << "String value = " << strn1 << endl;
    cout << "Integer value = " << val << endl;
 
    char strn2[] = "GeeksforGeeks";
    val = atoi(strn2);
    cout << "String value = " << strn2 << endl;
    cout << "Integer value = " << val << endl;
 
    return (0);
}
 
// This code is contributed by shivanisinghss2110




#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);
}




import java.util.*;
 
public class Main {
    public static void main(String[] args)
    {
        int val;
        String strn1 = "12546";
 
        val = Integer.parseInt(strn1);
        System.out.println("String value = " + strn1);
        System.out.println("Integer value = " + val);
 
        String strn2 = "GeeksforGeeks";
        try {
            val = Integer.parseInt(strn2);
            System.out.println("String value = " + strn2);
            System.out.println("Integer value = " + val);
        }
        catch (NumberFormatException e) {
            val = 0;
            System.out.println("String value = " + strn2);
            System.out.println("Integer value = " + val);
        }
    }
}




def main():
    strn1 = "12546"
    val = int(strn1)
    print("String value = ", strn1)
    print("Integer value = ", val)
 
    strn2 = "GeeksforGeeks"
    try:
        val = int(strn2)
    except ValueError:
        val = 0
        print("String value = ", strn2)
        print("Integer value = ", val)
 
 
if __name__ == "__main__":
    main()




using System;
 
namespace GeeksforGeeks {
class Program {
    static void Main(string[] args)
    {
        String strn1 = "12546";
        int val = int.Parse(strn1);
        Console.WriteLine("String value = " + strn1);
        Console.WriteLine("Integer value = " + val);
 
        String strn2 = "GeeksforGeeks";
        try {
            val = int.Parse(strn2);
        }
        catch (FormatException e) {
            val = 0;
            Console.WriteLine("String value = " + strn2);
            Console.WriteLine("Integer value = " + val);
        }
    }
}
}




// Javascript code to convert string to integer
let val;
let strn1 = "12546";
 
val = parseInt(strn1);
console.log("String value = " + strn1);
console.log("Integer value = " + val);
 
let strn2 = "GeeksforGeeks";
val = parseInt(strn2);
console.log("String value = " + strn2);
console.log("Integer value = " + val);
 
// This code is contributed by prasad264

Output

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

Complexity Analysis:

Now let’s understand various ways in which one can create their own atoi() function supported by various conditions:

Approach 1

The following is a simple implementation of conversion without considering any special case. 



Below is the implementation of the above approach:




// 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
    // 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; str[i] != '\0'; ++i)
        res = res * 10 + str[i] - '0';
 
    // return result.
    return res;
}
 
// Driver code
int main()
{
    char str[] = "89789";
 
    // Function call
    int val = myAtoi(str);
    cout << val;
    return 0;
}
 
// This is code is contributed by rathbhupendra




// 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
    // 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; str[i] != '\0'; ++i)
        res = res * 10 + str[i] - '0';
 
    // return result.
    return res;
}
 
// Driver Code
int main()
{
    char str[] = "89789";
 
    // Function call
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}




// 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
        // 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 = "89789";
 
        // Function call
        int val = myAtoi(str);
        System.out.println(val);
    }
}
 
// This code is contributed by PrinciRaj1992




# 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 range(len(string)):
        res = res * 10 + (ord(string[i]) - ord('0'))
 
    return res
 
 
# Driver program
string = "89789"
 
# Function call
print(myAtoi(string))
 
# This code is contributed by BHAVYA JAIN




// 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
        // 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[i] - '0';
 
        // return result.
        return res;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "89789";
 
        // Function call
        int val = myAtoi(str);
        Console.Write(val);
    }
}
 
// This code is contributed by Sam007.




<script>
// A simple Javascript program for
// implementation of atoi
 
// A simple atoi() function
function myAtoi(str)
{
    // Initialize result
        let 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 (let i = 0; i < str.length; ++i)
            res = res * 10 + str[i].charCodeAt(0) - '0'.charCodeAt(0);
  
        // return result.
        return res;
}
 
// Driver code
let str = "89789";
        
          
// Function call
let val = myAtoi(str);
document.write(val);
 
 
// This code is contributed by rag2127
</script>

Output
89789

Complexity Analysis:

Approach 2

This implementation handles the negative numbers.

Below is the implementation of the above approach:




// 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";
 
    // Function call
    int val = myAtoi(str);
    cout << val;
    return 0;
}
 
// This is code is contributed by rathbhupendra




// 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 code
int main()
{
    char str[] = "-123";
 
    // Function call
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}




// 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();
 
        // Function call
        int val = myAtoi(str);
        System.out.println(val);
    }
}
 
// This code is contributed by 29AjayKumar




# 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 range(i, len(string)):
        res = res*10+(ord(string[j])-ord('0'))
 
    return sign * res
 
 
# Driver code
string = "-123"
 
# Function call
print(myAtoi(string))
 
# This code is contributed by BHAVYA JAIN




// 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 code
    public static void Main()
    {
        string str = "-123";
 
        // Function call
        int val = myAtoi(str);
        Console.Write(val);
    }
}
 
// This code is contributed by Sam007.




<script>
 
    // JavaScript program for implementation of atoi
 
    // A simple atoi() function
    function myAtoi(str)
    {
  
        // Initialize result
        var res = 0;
  
        // Initialize sign as positive
        var sign = 1;
  
        // Initialize index of first digit
        var 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].charCodeAt(0) - '0'.charCodeAt(0);
  
        // Return result with sign
        return sign * res;
    }
  
      // Driver code
          var str = "-129";
          var val=myAtoi(str);
        document.write(val);
 
</script>
 <! --This code is contributed by nirajgusain5 -->

Output
-123

Complexity Analysis:

Approach 3

Four corner cases need to be handled:

Below are the steps for the above approach:

The other cases are handled in previous approaches. 

Dry Run:

Below is the implementation of the above approach: 




// 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;
}
 
// Driver Code
int main()
{
    char str[] = "  -123";
 
    // Functional Code
    int val = myAtoi(str);
    cout << " " << val;
    return 0;
}
 
// This code is contributed by shivanisinghss2110




// A simple C++ program for
// implementation of atoi
#include <limits.h>
#include <stdio.h>
 
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;
}
 
// Driver Code
int main()
{
    char str[] = "  -123";
 
    // Functional Code
    int val = myAtoi(str);
    printf("%d ", val);
    return 0;
}
// This code is contributed by Yogesh shukla.




// 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();
 
        // Function call
        int val = myAtoi(str);
        System.out.printf("%d ", val);
    }
}
 
// This code is contributed by 29AjayKumar




# A simple Python3 program for
# implementation of atoi
import sys
 
 
def myAtoi(Str):
 
    sign, base, i = 1, 0, 0
 
    # If whitespaces then ignore.
    while (Str[i] == ' '):
        i += 1
 
    # Sign of number
    if (Str[i] == '-' or Str[i] == '+'):
        sign = 1 - 2 * (Str[i] == '-')
        i += 1
 
    # Checking for valid input
    while (i < len(Str) and
           Str[i] >= '0' and Str[i] <= '9'):
 
        # Handling overflow test case
        if (base > (sys.maxsize // 10) or
            (base == (sys.maxsize // 10) and
                (Str[i] - '0') > 7)):
            if (sign == 1):
                return sys.maxsize
            else:
                return -(sys.maxsize)
 
        base = 10 * base + (ord(Str[i]) - ord('0'))
        i += 1
 
    return base * sign
 
 
# Driver Code
Str = list(" -123")
 
# Functional Code
val = myAtoi(Str)
 
print(val)
 
# This code is contributed by divyeshrabadiya07




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




<script>
// A simple JavaScript program for
// implementation of atoi
    function myAtoi(str)
   {
    var 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 > Number.MAX_VALUE/ 10
            || (base == Number.MAX_VALUE / 10
            && str[i] - '0' > 7))
        {
            if (sign == 1)
                return Number.MAX_VALUE;
            else
                return Number.MAX_VALUE;
        }
        base = 10 * base + (str[i++] - '0');
    }
    return base * sign;
}
 
    // Driver code
        var str = " -123";
       
        // Function call
        var val = myAtoi(str);
        document.write(" ", val);
     
// This code is contributed by shivanisinghss2110
</script>

Output
 -123

Complexity Analysis:

Related Articles:

Exercise:

Write your won atof() that takes a string (which represents a floating point value) as an argument and returns its value as double.

This article is compiled by Abhay Rathi.  


Article Tags :