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:
#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); } |
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:
-
Following is a simple implementation of conversion without considering any special case. We initialize result as 0. We start from the first character and update result for every character.
C
// Program to implement atoi() in C#include <stdio.h>// A simple atoi() functionintmyAtoi(char* str){intres = 0;// Initialize result// Iterate through all characters of input string and// update resultfor(inti = 0; str[i] !='\0'; ++i)res = res * 10 + str[i] -'0';// return result.returnres;}// Driver program to test above functionintmain(){charstr[] ="89789";intval = myAtoi(str);printf("%d ", val);return0;}chevron_rightfilter_noneC++
// A simple C++ program for implementation of atoi#include <bits/stdc++.h>usingnamespacestd;// A simple atoi() functionintmyAtoi(char* str){intres = 0;// Initialize result// Iterate through all characters of input string and// update resultfor(inti = 0; str[i] !='\0'; ++i)res = res * 10 + str[i] -'0';// return result.returnres;}// Driver codeintmain(){charstr[] ="89789";intval = myAtoi(str);cout << val;return0;}// This is code is contributed by rathbhupendrachevron_rightfilter_nonePython
# Python program for implementation of atoi# A simple atoi() functiondefmyAtoi(string):res=0# Iterate through all characters of input string and# update resultforiinxrange(len(string)):res=res*10+(ord(string[i])-ord('0'))returnres# Driver programstring="89789"printmyAtoi(string)# This code is contributed by BHAVYA JAINchevron_rightfilter_noneC#
// A simple C# program for implementation// of atoiusingSystem;classGFG {// A simple atoi() functionstaticintmyAtoi(stringstr){intres = 0;// Initialize result// Iterate through all characters of// input string and update resultfor(inti = 0; i < str.Length; ++i)res = res * 10 + str[i] -'0';// return result.returnres;}// Driver program to test above functionpublicstaticvoidMain(){stringstr ="89789";intval = myAtoi(str);Console.Write(val);}}// This code is contributed by Sam007.chevron_rightfilter_none
Output:89789
-
In the below implementation negative numbers have been handled.
C++
// A C++ program for implementation of atoi#include <bits/stdc++.h>usingnamespacestd;// A simple atoi() functionintmyAtoi(char* str){intres = 0;// Initialize resultintsign = 1;// Initialize sign as positiveinti = 0;// Initialize index of first digit// If number is negative, then update signif(str[0] =='-') {sign = -1;i++;// Also update index of first digit}// Iterate through all digits and update the resultfor(; str[i] !='\0'; ++i)res = res * 10 + str[i] -'0';// Return result with signreturnsign * res;}// Driver codeintmain(){charstr[] ="-123";intval = myAtoi(str);cout << val;return0;}// This is code is contributed by rathbhupendrachevron_rightfilter_noneC
// A C program for implementation of atoi#include <stdio.h>// A simple atoi() functionintmyAtoi(char* str){intres = 0;// Initialize resultintsign = 1;// Initialize sign as positiveinti = 0;// Initialize index of first digit// If number is negative, then update signif(str[0] =='-') {sign = -1;i++;// Also update index of first digit}// Iterate through all digits and update the resultfor(; str[i] !='\0'; ++i)res = res * 10 + str[i] -'0';// Return result with signreturnsign * res;}// Driver program to test above functionintmain(){charstr[] ="-123";intval = myAtoi(str);printf("%d ", val);return0;}chevron_rightfilter_nonePython
# Python program for implementation of atoi# A simple atoi() functiondefmyAtoi(string):res=0# initialize sign as positivesign=1i=0# if number is negative then update signifstring[0]=='-':sign=-1i+=1# Iterate through all characters of input string and update resultforjinxrange(i,len(string)):res=res*10+(ord(string[j])-ord('0'))returnsign*res# Driver programstring="-123"printmyAtoi(string)# This code is contributed by BHAVYA JAINchevron_rightfilter_noneC#
// C# program for implementation of atoiusingSystem;classGFG {// A simple atoi() functionstaticintmyAtoi(stringstr){// Initialize resultintres = 0;// Initialize sign as positiveintsign = 1;// Initialize index of first digitinti = 0;// If number is negative, then// update signif(str[0] =='-') {sign = -1;// Also update index of first// digiti++;}// Iterate through all digits// and update the resultfor(; i < str.Length; ++i)res = res * 10 + str[i] -'0';// Return result with signreturnsign * res;}// Driver program to test above functionpublicstaticvoidMain(){stringstr ="-123";intval = myAtoi(str);Console.Write(val);}}// This code is contributed by Sam007.chevron_rightfilter_none
Output:-123
-
This implementation handles various type of 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 numericboolisNumericChar(charx){return(x >='0'&& x <='9') ?true:false;}// A simple atoi() function. If the given string contains// any invalid character, then this function returns 0intmyAtoi(char* str){if(*str =='\0')return0;intres = 0;// Initialize resultintsign = 1;// Initialize sign as positiveinti = 0;// Initialize index of first digit// If number is negative, then update signif(str[0] =='-') {sign = -1;i++;// Also update index of first digit}// Iterate through all digits of input string and update resultfor(; str[i] !='\0'; ++i) {if(isNumericChar(str[i]) ==false)return0;// You may add some lines to write error message// to error streamres = res * 10 + str[i] -'0';}// Return result with signreturnsign * res;}// Driver program to test above functionintmain(){charstr[] ="-134";intval = myAtoi(str);printf("%d ", val);return0;}chevron_rightfilter_nonePython
# Python program for implementation of atoi# A utility function to check whether x is numericdefisNumericChar(x):if(x >='0'andx <='9'):returnTruereturnFalse# A simple atoi() function. If the given string contains# any invalid character, then this function returns 0defmyAtoi(string):iflen(string)==0:return0res=0# initialize sign as positivesign=1i=0# if number is negative then update signifstring[0]=='-':sign=-1i+=1# Iterate through all characters of input string and update resultforjinxrange(i,len(string)):# You may add some lines to write error message to error streamifisNumericChar(string[j]==False):return0res=res*10+(ord(string[j])-ord('0'))returnsign*res# Driver programstring="-134"printmyAtoi(string)# This code is contributed by BHAVYA JAINchevron_rightfilter_noneTime Complexity: O(n) where n is the number of characters in the input string.
We only need to handle four cases:
- Discards all leading whitespaces
- sign of the number
- overflow
- invalid input
Below image is a dry run of the above approach:

Below is the implementation of the above approach:
// A simple C++ program for implementation of atoi#include <bits/stdc++.h>usingnamespacestd;intmyAtoi(constchar* str){intsign = 1, base = 0, i = 0;// if whitespaces then ignore.while(str[i] ==' ') {i++;}// sign of numberif(str[i] =='-'|| str[i] =='+') {sign = 1 - 2 * (str[i++] =='-');}// checking for valid inputwhile(str[i] >='0'&& str[i] <='9') {// handling overflow test caseif(base > INT_MAX / 10 || (base == INT_MAX / 10 && str[i] -'0'> 7)) {if(sign == 1)returnINT_MAX;elsereturnINT_MIN;}base = 10 * base + (str[i++] -'0');}returnbase * sign;}intmain(){charstr[] =" -123";intval = myAtoi(str);printf("%d ", val);return0;}// This code is contributed by Yogesh shukla.chevron_rightfilter_noneOutput :
-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
- Count of lines required to write the given String
- Write a program to reverse an array or string
- Write a program to print all permutations of a given string
- Write Code to Determine if Two Trees are Identical
- Write an Efficient Method to Check if a Number is Multiple of 3
- Write a function to get the intersection point of two Linked Lists
- Write an Efficient C Program to Reverse Bits of a Number
- 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
- Reduce the number to minimum multiple of 4 after removing the digits
- Microsoft Interview Experience for Software Engineer | On-Campus 2019


