Write your own atoi()
The atoi() function takes a string (which represents an integer) as an argument and returns its value.
Following is a simple implementation. We initialize result as 0. We start from the first character and update result for every character.
C/C++
// A simple C program for implementation of atoi #include <stdio.h> // A simple atoi() function int myAtoi(char *str) { int res = 0; // Initialize result // 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; } |
Python
# 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 |
C#
// 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. |
Output:
89789
The above function doesn’t handle negative numbers. Following is a simple extension to handle negative numbers.
C
// A C program for implementation of atoi #include <stdio.h> // A simple atoi() function int myAtoi(char *str) { int res = 0; // Initialize result int sign = 1; // Initialize sign as positive int i = 0; // Initialize index of first digit // If number is negative, then update sign if (str[0] == '-') { sign = -1; i++; // Also update index of first digit } // 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; } |
Python
# 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 |
C#
// 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. |
Output:
-123
The above implementation doesn’t handle errors. What if str is NULL or str contains non-numeric characters. Following implementation handles errors.
C++
// 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; int res = 0; // Initialize result int sign = 1; // Initialize sign as positive int i = 0; // Initialize index of first digit // If number is negative, then update sign if (str[0] == '-') { sign = -1; i++; // Also update index of first digit } // Iterate through all digits of input string and update result for (; str[i] != '\0'; ++i) { if (isNumericChar(str[i]) == false) return 0; // You may add some lines to write error message // 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; } |
Python
# 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 |
Time Complexity: O(n) where n is the number of characters in input string.
We only need to handle four cases:
In below implementation all above four cases can be handle.
// 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. |
Output :
-123
Time Complexity O(n), where n is length of string.
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.
Recommended Posts:
- Recursive Implementation of atoi()
- Write a program to calculate pow(x,n)
- Write your own strcmp that ignores cases
- Write a program to reverse an array or string
- Write Code to Determine if Two Trees are Identical
- Write a program to print all permutations of a given string
- Count of lines required to write the given String
- Write an Efficient Method to Check if a Number is Multiple of 3
- Write an Efficient C Program to Reverse Bits of a Number
- Write a function to get the intersection point of two Linked Lists.
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a function that returns 2 for input 1 and returns 1 for 2
- Count of pairs of strings which differ in exactly one position
- Count of sub-strings that do not contain all the characters from the set {'a', 'b', 'c'} at the same time
Improved By : Yogesh Shukla 1



