Implement atoi function in C | Iterative & Recursive

Write an efficient function to implement atoi function in C. Standard atoi() function convert 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

 
Above iterative and recursive implementations 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 –

 

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 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz