Atoi - InterviewBit Solution

Problem: Atoi


Problem Description:

Implement atoi to convert a string to an integer.


Example :

Input : "9 2704" Output : 9

Note: There might be multiple corner cases here. Clarify all your doubts using “See Expected Output”.


Questions: Q1. Does string contain whitespace characters before the number? A. Yes Q2. Can the string have garbage characters after the number? A. Yes. Ignore it. Q3. If no numeric character is found before encountering garbage characters, what should I do? A. Return 0. Q4. What if the integer overflows? A. Return INT_MAX if the number is positive, INT_MIN otherwise.



Solution Approach:

There are few corner cases to consider here:

  1. Ignore space characters at the beginning.

  2. Check for its sign

  3. Ignore the garbage characters after integer

  4. Check for overflow

The code has been commented out to understand the logic for the above cases.



Solution:

In C++