C++ Concise 13 line solution beats 100%


  • 0
    R

    The idea is the same and the use of isdigit and find_first_not_of helps improve the run-time and beats 100% of submitted solutions.

    class Solution {
    public:
        int myAtoi(string str) {
        long result = 0;
        int sign = 1;
        int i = str.find_first_not_of(' ');
            if(str[i] == '-' || str[i] == '+')
                sign = 1 - 2 * (str[i++] == '-');
            while(isdigit(str[i])) 
            {
                result = result*10 + (str[i++]-'0');
                if(result*sign >= INT_MAX) return INT_MAX;
                if(result*sign <= INT_MIN) return INT_MIN;                
            }
    return result*sign;    
    }
    };
    ``

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.