![]() |
VOOZH | about |
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:
String value = 12546 Integer value = 12546 String value = GeeksforGeeks Integer value = 0
Time Complexity : O(N)
Auxiliary Space : O(1) , as no extra space is needed.
Now let's understand various ways in which one can create their own atoi() function supported by various conditions:
Following is a simple implementation of conversion without considering any special case.
89789
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.
-123
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
Four corner cases needs to be handled:
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:
-123
Complexity Analysis for all the above Approaches:
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!