string to integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.


Input Validdation:

1. starts by '  '

2. followed possible spaces should be '+/-', and no space is allowed later

3. after the single +/-, only 0-9

4. must take care of INT overflow


class Solution {
public:
    int atoi(const char *str) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(str==NULL)
            return 0;
        
        int flag=1;
        long long val=0;
        const char *p=str;
        
        
        for(int i=0; *p!='\0' ; p++)//i>0 only if a 0-9 appears
        {
            if( i==0 && (*p=='+' || *p=='-') )//' 'is only allowed before '+/-
            {
                i++;
                if(*p=='-') flag=-1;
                continue;
            }
            else if(i==0 && *p==' ') continue;
           
            if(*p<'0' || *p>'9')
            {
                //invalid input, then return the current valid number
                return (int)val*flag;
            }
            else{
                val=(long long)10*val+(long long)(*p-'0');
                
                if(val > INT_MAX && flag==1) 
                    return INT_MAX; //check whether overflow int. If is, return INT_MAX
                else if(val > INT_MAX)
                    return INT_MIN;
                    
                i++;
            }
        }
        
        return (int)val*flag;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章