C++ atoi question...need your help


  • 0
    N

    Hi! I thought this should work. however runtime error...
    somebody help me find out where is not ok?
    Thankds

    enter code here
    
    class Solution {public:
        int myAtoi(string str) {
            if (str=="") return 0;
            auto beg=str.find_first_not_of(" ");
            if (beg==-1) return 0;
            string s1(str, beg);
            bool neg=false;
            if (s1[0]=='-') {
                neg=true;
                if (s1.size()==1) return 0;
            }
            string s2=(s1[0]=='-')?s1.substr(1):s1;
            auto end=s2.find_first_not_of("0123456789");
            string s3=(end==-1)?s2:s2.substr(0,end);
            if(s3=="") return 0;
            vector<int> num;
            for(int i=0;i<end;i++){
                switch(s3[i]){
                    case '0':
                        num.push_back(0);
                        break;
                    case '1':
                        num.push_back(1);
                        break;
                    case '2':
                        num.push_back(2);
                        break;
                     case '3':
                        num.push_back(3);
                        break;
                    case '4':
                        num.push_back(4);
                        break;
                    case '5':
                        num.push_back(5);
                        break;
                     case '6':
                        num.push_back(6);
                        break;
                    case '7':
                        num.push_back(7);
                        break;
                    case '8':
                        num.push_back(8);
                        break;
                    case '9':
                        num.push_back(9);
                        break;
         }
            }
            auto size=num.size();
            long long int number=0;
            for(int j=0;j<size;j++){
                
                number+=num[j]*pow(10,size-1-j);
            }
            if(number>INT_MAX+1) return 0;
            else if(number==INT_MAX+1 && !neg) return 0;
            
            if(neg) return -number;
            else    return number;
            
        }
    };

  • 0
    W

    u can use isdigit() and s[i]-'0' instead of swich
    if more than INT_MAX should return INT_MAX not 0;


Log in to reply
 

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