String to Integer (atoi) - C++


  • 0
    L

    '''
    class Solution {
    public:
    int myAtoi(string str) {

        string resContain="1234567890";
        int c1=0;
        int start=0;
        int pls = 1;
        int ft=1;
        int prop=0;
        if(str.length()==0) return 0;
        
        for(int i=0;i<str.length();i++)
        {
            if(str[i]==' '&&ft) 
            {
                continue;
            }
            else if(str[i]=='+')
            {
                ft=0;
                if(prop==1) return 0;
                 prop=1;                
                 pls=1;
            }
            else if(str[i]=='-'){
                ft=0;
                if(prop==1) return 0;
                 prop=1;                 
                 pls=-1;
            }
            else
            {
                ft=0;
                start=str[i]-'0';
                
                if(start>=0&&start<=9)
                {
                 if(c1>214748364) return pls>0?2147483647:-2147483648;
                 else if(c1==214748364&&pls==1) if(start>7) return 2147483647;
                 else if(c1==214748364&&pls==-1) if(start>8) return -2147483648;
    
                 c1*=10;
                 c1+=start;   
                }
                else
                {
                    break;
                }                
                
            }
            
           
        }
        
        int num =pls*c1;
            if(c1>2147483647&&pls==1)
            {
                 return 2147483647;
            }                     
           else if(c1<0)
           {
               return -2147483648;
           }           
           else
           {
               return num;
           }
    }
    

    };
    '''


Log in to reply
 

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