Implement atoi() function in C | Iterative & Recursive implementation

Write an efficient function to implement atoi function in C. Standard atoi() function convert input C-string to its corresponding integer value.

 

Iterative Implementation:

C

Download   Run Code

Output:

12345

Recursive Implementation:

C

Download   Run Code

Output:

12345

Above iterative and recursive implementation of atoi() is not similar to 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 contain any additional characters after those that form the integral number are ignored. No conversion is performed if string is empty or it only contains whitespace characters and zero is returned. Below atoi() implementation takes care of all these –

C

Download   Run Code

Output:

-1234567890

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂