Solution with if-else conditions only :)


#1

int Solution::atoi(const string s) {
stack stk;
int state = 0;
int sign = 1;
for(char ch: s){
if(ch != 32 && state == 0){
if(ch == 45){
sign = -1;
state = 1;
continue;
}
if(ch == 43){
state = 1;
continue;
}
if(!(ch >= 48 && ch <= 57)){
state = -1;
break;
}
stk.push(ch);
state = 1;
continue;
}
else if(ch == 32 && state == 0)
continue;
else if(state == 1){
if(ch >= 48 && ch <= 57){
stk.push(ch);
}
else{
break;
}
}
}
if(state == -1){
return 0;
}
if(stk.size() > 10){
if(sign == 1)
return INT_MAX;
else
return INT_MIN;
}

int x = INT_MAX - 2000000000;
int y = -1*(INT_MIN + 2000000000);
int res = 0;
int tens = 0;

if(stk.size() < 10){
    while(!stk.empty()){
        res += (int)(stk.top()-'0')*pow(10, tens);
        stk.pop();
        tens++;
    }
    return sign*res;
}
else{
    while(stk.size() > 1){
        res += (int)(stk.top()-'0')*pow(10, tens);
        stk.pop();
        tens++;
    }
    if(stk.top() > 2){
        if(sign == 1)
            return INT_MAX;
        else
            return INT_MIN;
    }
    if(stk.top() < 2){
        res += (int)(stk.top()-'0')*pow(10, tens);
        return sign*res;
    }
    else{
        if(sign == 1){
            if(res >= x)
                return INT_MAX;
            else{
                res += (int)(stk.top()-'0')*pow(10, tens);
                return res;
            }
        }
        else{
            if(res >= y)
                return INT_MIN;
            else{
                res += (int)(stk.top()-'0')*pow(10, tens);
                return -1*res;
            }
        }
    }
}

}