C++ code with queue


  • 0
    S
    class Solution {
    public:
        int calculate(string s) {
            queue<int> numq;
            queue<char> signq;
            int todo_num;
            char todo_sign = 0;
            char sign;
            int num = 0;
            int n1, n2;
            for(char c : s)
            {
                if(isdigit(c))
                {
                    num = num*10 + c - '0';
                }
                else if(c == '+' || c == '-')
                {
                    if(todo_sign != 0)
                    {
                        if(todo_sign == '*')
                            num = todo_num * num;
                        else if(todo_sign == '/')
                            num = todo_num / num;
                        todo_sign = 0;
                    }
                    numq.push(num); num = 0;
                    signq.push(c);
                }
                else if(c == '*' || c == '/')
                {
                    if(todo_sign == '*')
                        todo_num = todo_num * num;
                    else if(todo_sign == '/')
                        todo_num = todo_num / num;
                    else
                        todo_num = num;
                    todo_sign = c;
                    num = 0;
                }
            }
            if(todo_sign == '*')
                num = todo_num*num;
            if(todo_sign == '/')
                num = todo_num / num;
            numq.push(num);
            n1 = numq.front(); numq.pop();
            while(signq.size() > 0)
            {
                sign = signq.front(); signq.pop();
                n2 = numq.front(); numq.pop();
                if(sign == '+')
                    n1 = n1 + n2;
                else if(sign == '-')
                    n1 = n1 - n2;
            }
            return n1;
        }
    };

Log in to reply
 

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