Readable solution in C, 4 ms


  • 4
    S
    int charToInteger(char c) {
        if (c < 48 || c > 57) return -1;
        return c - 48;
    }
    
    int myAtoi(char* str) {
        
        // remove whitespaces
        while(strlen(str) > 0 && isspace(str[0])) str++;
        
        // detect +/- sign
        bool negative = false;
        if(strlen(str) > 0 && str[0] == '-') {
            str++;
            negative = true;
        } else if (strlen(str) > 0 && str[0] == '+') {
            str++;
        }
        
        // parse the digits
        int numberValue = 0;
        for(int i = 0; i < strlen(str) ;i++) {
            
            int currentValue = charToInteger(str[i]);
            if(currentValue == -1) break;
            
            if(negative && numberValue < -214748364) return -2147483648; // number would underflow *10
            if(!negative && numberValue > 214748364) return 2147483647; // number would overflow by *10
            numberValue *= 10;
            
            numberValue = negative ? (numberValue - currentValue) : (numberValue + currentValue);
            
            if(negative && numberValue > 0) return -2147483648; // did underflow
            if(!negative && numberValue < 0) return 2147483647; // did overflow
            
        }
        
        return numberValue;
    }

  • 0
    D

    how you deal with overflow enlightened me.


  • 0
    S

    this does not completely solve the overflow if it is 2147483649


  • 0
    S

    I believe it does, the second check in the loop will catch that underflow. It's because the negative number becomes positive and that means the underflow happened.

    In the last loop of the for-cycle the values will be like this:

        // currentValue = 9
        // numberValue = -214748364
        
        /* ... first check, not returning ... */
        
        numberValue *= 10; 
        // numberValue = -2147483640
    
        numberValue = negative ? (numberValue - currentValue) : (numberValue + currentValue);
        // numberValue = -2147483649 --> underflow by 1 --> numberValue = +2147483647
    
        // second check, returning, negative number became positive
        if(negative && numberValue > 0) return -2147483648;
    

Log in to reply
 

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