본문 바로가기

C

c++ leet code 227, Basic CalculatorII code

code >>

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using namespace std;
class Solution {
public:
    int calculate(string s) {
        stack<int> num_stack;
        int answer = 0;
        int len = (int)s.size();
        int currentNumber = 0;
        char operation = '+';
        for (int i = 0; i < len; i++)
        {
            if (isdigit(s[i]))
            {
                int num = s[i] - '0';
                currentNumber = currentNumber * 10 + num;
            }
            if ((!isdigit(s[i]) && (!iswspace(s[i]))) || (i == len - 1))
            {
                if (operation == '+')
                {
                    num_stack.push(currentNumber);
                }
                else if (operation == '-')
                {
                    num_stack.push(-currentNumber);
                }
                else if (operation == '*')
                {
                    int tmp_top = num_stack.top();
                    tmp_top = tmp_top * currentNumber;
                    num_stack.pop();
                    num_stack.push(tmp_top);
                }
                else if (operation == '/')
                {
                    int tmp_top = num_stack.top();
                    tmp_top = tmp_top / currentNumber;
                    num_stack.pop();
                    num_stack.push(tmp_top);
                }
                currentNumber = 0;
                
                operation = s[i];
            }
        }
 
        int stack_size = num_stack.size();
        for (int i = 0; i < stack_size; i++)
        {
            answer = answer + num_stack.top();
            num_stack.pop();
        }
 
        return answer;
    }
    
};