Coding-Interview-101

Solutions to LeetCode problems filtered with companies, topics and difficulty.

View project on GitHub

String to Integer (atoi)


Solution


    class Solution {
    public:
        int myAtoi(string s) {
            long int ans = 0;
            bool pos = true;
            int i = 0;
            while(s[i] == ' ')
                i++;
            if(s[i] == '-')
                pos = false;
            if(!pos || s[i] == '+')
                i++;
            while(s[i] >= '0' && s[i] <= '9') {
                ans = ans * 10 + (s[i] - '0');
                i++;
                if(ans > INT_MAX && !pos)
                    return INT_MIN;
                else if(ans > INT_MAX && pos)
                    return INT_MAX;
            }
            return pos ? (int)ans : -(int)ans;
        }
    };