Saturday, September 7, 2013

String to Integer (atoi)

Implement atoi to convert a string to an integer.
Solution : 
Code:
class Solution {
public:
    int atoi(const char *str) {
      
       if (*str =='\0') return 0;
       // skip whitespaces.
       while ((*str) == ' ') str++;
       // sign
       int sign = 1;
       if(*str == '-')
       {
            sign = -1;
            str++;
       }
       else if(*str == '+')
       {
           sign = 1;
           str++;
       }
       // convert to number
       int num = 0;
       while (isdigit(*str))
       {
            if(((num == 214748364) && ((*str) - '0' >7)) || (num > 214748364))
            return (sign>0? INT_MAX : INT_MIN);
            num = num*10 + ((*str)-'0');
            str++;
       }
       return (sign*num);
    }
};

No comments:

Post a Comment