Write an efficient function to implement atoi() function in C. The standard atoi() function converts input C-string to its corresponding integer value.

Iterative Implementation of atoi():

Download  Run Code

Output:

12345

Recursive Implementation of atoi():

Download  Run Code

Output:

12345

 
The above iterative and recursive implementations of atoi() is not similar to the standard implementation of atoi(). The function should first discard as many whitespace characters until the first non-whitespace character is found. Then, starting from this character takes an optional initial plus or minus sign, followed by as many base-10 digits as possible, and interprets them as a numerical value. The string, if it contains any additional characters after those that form the integral number, are ignored. No conversion is performed if the string is empty or only contains whitespace characters and zero is returned. Following atoi() implementation takes care of all these:

Download  Run Code

Output:

-1234567890

 
The time complexity of all the above solutions is O(n), where n is the length of the input string.

That’s all about atoi() implementation in C.