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 their 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’)
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" # Function call print myAtoi(string) # This code is contributed by BHAVYA JAIN |
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.
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 code string = "-123" # Function call print myAtoi(string) # This code is contributed by BHAVYA JAIN |
-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:
Python
# A simple Python3 program for # implementation of atoi import sys def myAtoi(s): i, base, sign = 0 , 0 , 1 # handle the case where s contains no digits (or input is malformed) if not ( set (s) & set ( '0123456789' )): return 0 # increment past whitespace (ignore) while s[i] = = ' ' : i + = 1 # compute sign (2s complement) if s[i] = = '-' or s[i] = = '+' : sign = 1 - 2 * (s[i] = = '-' ) i + = 1 # loop as long as the next input is a digit while i < len (s) and '0' < = s[i] < = '9' : # test for overflow if (base > (sys.maxsize / / 10 ) or (base = = (sys.maxsize / / 10 ) and ( ord (s[i]) - ord ( '0' )) > 7 )): # clamp to +/- maxsize if sign = = 1 : return sys.maxsize else : return - (sys.maxsize) - 1 base = 10 * base base + = ( ord (s[i]) - ord ( '0' )) i + = 1 return base * sign # Driver Code s = " 123" # Functional Code val = myAtoi(s) print (val) # This code is contributed by divyeshrabadiya07, justinalangley |
-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.
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!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!