Leetcode – String to Integer (atoi)

Name: String to Integer (atoi)
Difficulty: Medium
Description: Convert a string to an integer as per the C++ atoi function

Example:

Input: s = "42"
Output: 42

Input: s = "   -42"
Output: -42

Input: s = "4193 with words"
Output: 4193

This is a pretty straight forward solution, I enjoy writing code that parses text.

int myAtoi(string s) {
    if (s.empty()) return 0;

    bool processing{false};
    char sign{ 0 };
    long long num{0};

    for(char c : s) {
        if (!processing) {
            if (c == ' ') {
                if (sign != 0) return 0;
                continue;
            }

            if (c == '+' || c == '-') {
                if (sign != 0) return 0;
                sign = c;
                continue;
            }

            processing = true;
        }

        if (c < '0' || c > '9') break;

        num = num * 10 + (c - '0');

        if ((sign == 0 || sign == '+') && num >= INT_MAX) return INT_MAX;
        if (sign == '-' && num > INT_MAX) return INT_MIN;
    }

    if (num == 0) return 0;

    if (sign == 0 || sign == '+') return (int)num;
    return (int)num * -1;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s