C++: String to Integer (atoi)

Thought Process

To convert a string to an integer, we need to handle leading whitespaces, sign characters ('+' or '-'), and numeric characters. We iterate through the string, skipping leading spaces, and then check for a sign. After that, we process the numeric characters to build the integer. If the result exceeds the 32-bit signed integer range, we clamp it to INT_MIN or INT_MAX. This ensures we handle edge cases and invalid inputs gracefully.

class Solution {
public:
    int myAtoi(string s) {
        
        long ans = 0;
        bool isFirstCharacter = true;
        int sign = 1;

        for(int i=0;i<s.size();i++){

            char ch = s[i];
            if(ch==' '){
                if(isFirstCharacter)
                    continue;
                else
                    break;
            }
            else if(ch=='+' || ch=='-'){

                if(ch=='+'){
                    if(isFirstCharacter==true){
                        sign = 1;
                        isFirstCharacter = false;
                    }
                    else 
                        break;
                }
                else if(ch=='-'){
                    if(isFirstCharacter==true){
                        sign = -1;
                        isFirstCharacter = false;
                    }
                    else 
                        break;
                }
            }
            else if(isdigit(ch)){
                ans = ans*10 + ch-'0';
                isFirstCharacter = false;

                if(ans*sign <= INT_MIN)
                    return INT_MIN;
                else if(ans*sign >= INT_MAX)
                    return INT_MAX;
            }
            else
                break;
        }
        return (int)ans*sign;
    }
};

Code Complexity

Time Complexity: O(n)

The algorithm iterates through the string once, making it linear in time complexity.

Space Complexity: O(1)

The algorithm uses a constant amount of extra space, regardless of the input size.

Code copied!