AlgoMaster Logo

Basic Calculator II

s=3+2*2
1public int calculate(String s) {
2    Stack<Integer> stack = new Stack<>();
3    int num = 0;
4    char lastSign = '+';
5
6    for (int i = 0; i < s.length(); i++) {
7        char c = s.charAt(i);
8        if (Character.isDigit(c)) {
9            num = num * 10 + (c - '0');
10        }
11
12        if (!Character.isDigit(c) && c != ' ' || i == s.length() - 1) {
13            if (lastSign == '+') {
14                stack.push(num);
15            } else if (lastSign == '-') {
16                stack.push(-num);
17            } else if (lastSign == '*') {
18                stack.push(stack.pop() * num);
19            } else if (lastSign == '/') {
20                stack.push(stack.pop() / num);
21            }
22
23            if (!Character.isDigit(c) && c != ' ') {
24                lastSign = c;
25            }
26            num = 0;
27        }
28    }
29
30    int result = 0;
31    for (int number : stack) {
32        result += number;
33    }
34    return result;
35}
0 / 24
3+2*2stack