Sunday, November 30, 2014

String to Integer (atoi)

 To deal with overflow, inspect the current number before multiplication. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than 7.(remember INT_MAX  is 2147483647)

    int atoi(const char *str) {
            int num=0; 
            int sign =1; 
            int i =0; 
            while(str[i] == ' ') {i++;} 
           
            if(str[i] == '+'||str[i] == '-'){
                sign=str[i] == '+'?1:-1;
                i++;
            }  
           
            while(str[i]>='0' && str[i] <= '9')
            { 
                 if(str[i] == ' ') break; 
                 if(INT_MAX/10 < num || INT_MAX/10 == num && INT_MAX%10 < (str[i] -'0')) 
                     return sign == -1 ? INT_MIN : INT_MAX; 
                 num = num*10 + str[i++] -'0'; 
            } 
            return num*sign; 
    }

No comments:

Post a Comment