C++ solution using int


  • 0
    K

    int atoi(string str) {

        int sign = 1;
        int index = 0;
        while ( index < str.length ( ) )
        {
            // Digit found, break to start processing
            if ( str [ index ] >= '0' && str [ index ] <= '9' )
                break;
            // Positive sign, increment index to start processing next character and break
            else if ( str [ index ] == '+' )
            {
                ++index;
                break;
            }
            // Negative sign
            else if ( str [ index ] == '-' )
            {
                sign = -1;
                ++index;
                break;
            }
            // Space found, skip it
            else if ( str [ index ] == ' ' )
            {
                ++index;
                continue;
            }
            // Not a space or + or -, invalid character. Return 0
            else
                return 0;
            
            ++index;
        }
        
        int accum = 0;
        for ( int i = index; i < str.length ( ); ++i )
        {
            // At this point, we should either find digits only. If anything else found, break and return whatever we have
            if ( str [ i ] >= '0' && str [ i ] <= '9' )
            {
                // Calculate current value
                int value = sign * ( str [ i ] - '0' );
                
                // Simply, if accum > ( INT_MAX / 10 ), then accum * 10 will overflow, break and return INT_MAX
                // If accum == ( INT_MAX / 10 ), then ( accum * 10 ) + value should be less than or equal INT_MAX, which
                // implies that value should be less than or equal to INT_MAX % 10
                // Example:
                // INT_MAX = 123
                // INT_MAX / 10 = 12
                // INT_MAX % 10 = 3
                // value should be less than or equal 3
                if ( ( accum > INT_MAX / 10 ) || ( accum == INT_MAX / 10 && value > INT_MAX % 10 ) )
                {
                    accum = INT_MAX;
                    break;
                }
                // Same as positive sign condition, but this time using INT_MIN
                else if ( ( accum < INT_MIN / 10 ) || ( accum == INT_MIN / 10 && value < INT_MIN % 10 ) )
                {
                    accum = INT_MIN;
                    break;
                }
                
                accum *= 10;
                accum += value;
            }
            // Not a digit, break
            else
                break;
        }
        
        return accum;
        
    }

Log in to reply
 

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