8ms C++ with long container


  • 0
    C

    This pretty much bare-bone C after very first statement.

    int atoi(std::string& st) {
        const char* str = st.c_str();
        bool negative= false;
        // skip white space
        while (*str && (*str==' ' || *str=='\t')) ++str;
        if (!*str)
             return 0;
        if (*str=='-' || *str=='+')
             negative = *str++ =='-' ? true: false;
        
        long res= 0; // accumulate in a bigger container
        for (;
              *str &&                      // while there is more
              *str>='0' && *str<='9' &&  // numbers from 0~9
              res< (long)INT_MAX+1       // without result overflowing
             ; ++str)
          res = res*10 + *str - '0' ;
         
        res = negative ? -res: res;       // apply sign
        return res > INT_MAX ? INT_MAX :  // clamp on to MIN, MAX boundaries
               res < INT_MIN ? INT_MIN : res ;
    
    }

  • 1

    Just removed some pointless stuff here and there, mostly the constant *str checking and the ? true: false (I just can't stand that one).

    int myAtoi(string st) {
        const char* str = st.c_str();
        bool negative = false;
        while (*str==' ') ++str;
        if (*str=='-' || *str=='+')
             negative = *str++ == '-';
    
        long res = 0;
        while (*str>='0' && *str<='9' && res<INT_MAX)
          res = res*10 + *str++ - '0';
    
        res = negative ? -res: res;
        return res > INT_MAX ? INT_MAX :
               res < INT_MIN ? INT_MIN : res ;
    }
    

    Another, slightly tricky handling of signs:

        int sign = 1;
        if (*str=='-' || *str=='+')
            sign = 44 - *str++;
        res *= sign;
    

    Or you could do that but use a ternary again:

            sign = *str++ == '-' ? -1 : 1;
    

  • 0
    C

    thanks ! first sign trick is bit hacky. I would go for the second. Will leave my code unchanged so, your answer is still relevant.


  • 0
    J

    Using long as a "bigger container" is error-prone, coz the size of long and int is implementation dependent. C++ standard does not specify explicitly what size is for int and long int. Rather, it only specifies the minimum size requirement. There ARE implementations where int and long are both 32bit long.


Log in to reply
 

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