String to Integer (atoi)

 

    int atoi(const char *str) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        //skip whitespace
        const char* p = str;
        while(*p==' ') 
            ++p;  
        if(*p!='+'&&*p!='-'&&!isdigit(*p))
            return 0;
        bool bNegative = false;
        if(*p=='+')
            p++;
        else if(*p=='-')
        {
            bNegative = true;
            p++;
        }
        
        long long sum = 0;
        while(*p&&isdigit(*p))
        {
            sum = sum*10+(*p-'0');
            if(sum>=(long long)INT_MAX+1)
               return (bNegative?INT_MIN:INT_MAX);
            p++;
        }
        return (bNegative?-sum:sum);
    }

  

posted @ 2013-10-04 21:52  summer_zhou  阅读(145)  评论(0编辑  收藏  举报