High quality code in c++ (takes 8ms)


  • 0
    V

    This code is commented and put emphasis on both the preformance and the quality of the code.

    int myAtoi(string str) {
        int i=0, sign = 1;
        long int num = 0;
        
        //remove the whitespaces
        while (isspace(str[i])) i++;
        
        //get the sign
        if ('+' == str[i]) i++;
        else if ('-' == str[i]) {
            sign = -1;
            i++;
        }
        
        //create the number
        while (str[i]>='0' && str[i]<='9') {
            num = num*10 + str[i]-'0';
            
            //if outside the limit, return limit
            if (sign*num > INT_MAX) return INT_MAX;
            else if (sign*num < INT_MIN) return INT_MIN;
            
            i++;
        }
        //ignore the other chars
        
        return (int)sign*num;
    }

  • 0
    D

    INT_MAX? it is for 16bit integer.. I'm confused.


  • 0
    V

    INT_MAX represents maximum value for data type 'int'.

    the actual value depends on the particular system and library implementation,
    but shall reflect the limits of these types in the target platform.

    (reference - http://www.cplusplus.com/reference/climits/)


Log in to reply
 

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