Why wrong answers?


  • 0
    S

    I write my own code to convert the string into integer. But it seems that something wrong with it. Only when I use atoi(tokens[i].c_str()) to get the number, can I pass the tests. Can anybody tell me what's wrong with my own converting code?

    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            stack<int> s;
            for(int i = 0; i < tokens.size(); i++){
                if(tokens[i].size() > 1 || (tokens[i][0] != '+' && tokens[i][0] != '-' && tokens[i][0] != '*' && tokens[i][0] != '/')){
                    int j = 0;
                    int tmp;
                    if(tokens[i][j] != '-'){
                        tmp = tokens[i][0] - '0';
                        j++;
                    }
                    else{
                        tmp = -(tokens[i][1] - '0');
                        j += 2;
                    }
                    for(; j < tokens[i].size(); j++)
                        tmp = tmp*10 + (tokens[i][j] - '0');
                    s.push(tmp);
                }
                else{
                    int tmp1 = s.top();
                    s.pop();
                    int tmp2 = s.top();
                    s.pop();
                    if(tokens[i][0] == '+') s.push(tmp2+tmp1);
                    else if(tokens[i][0] == '-') s.push(tmp2-tmp1);
                    else if(tokens[i][0] == '*') s.push(tmp2*tmp1);
                    else s.push(tmp2/tmp1);
                }
            }
            return s.top();
        }
    };

Log in to reply
 

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