These problem can be surely solved by OPG. However, since they are just basic calculator. They can still be solved by some simple code.
For calculator 1, we need the help of a stack. Every time when we see a ‘(‘, we store the result and sign in stack. When we see ‘)’, we pop sign and number and calculate them with current number.
For calculator 2, if we encounter ‘+’ or ‘-‘, we simply calculate and put in a stack. If we encounter ‘*’ or ‘/’, we need to pop sign stack and number stack, and calculate with current number, then put back to stack.
Calculator 1:
"1 + 1" = 2 " 2-1 + 2 " = 3 "(1+(4+5+2)-3)+(6+8)" = 23
public static int calculate(String s) { Stack<Integer> stack = new Stack<>(); int result = 0, sign = 1; for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == ' ') { continue; } else if (Character.isDigit(ch)) { int num = 0; for (; i < s.length() && Character.isDigit(s.charAt(i)); i++) { num = num * 10 + (s.charAt(i) - '0'); } result += num * sign; i--; } else if (ch == '+') { sign = 1; } else if (ch == '-') { sign = -1; } else if (ch == '(') { stack.push(result); stack.push(sign); result = 0; sign = 1; } else if (ch == ')') { result = stack.pop() * result + stack.pop(); } } return result; }
Code for calculator 2:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
public static int calculate(String s) { Stack<Integer> stack = new Stack<>(); int num = 0, len = s.length(); char sign = '+'; for (int i = 0; i < len; i++) { char ch = s.charAt(i); if (ch == ' ' && i != len - 1) { continue; } if (Character.isDigit(ch)) { num = num * 10 + (ch - '0'); } // it means this one is a sign or it is the end. Use previous one to calculate if (ch < '0' || ch > '9' || i == len - 1) { switch (sign) { case '+': stack.add(num); break; case '-': stack.add(-num); break; case '*': stack.add(stack.pop() * num); break; case '/': stack.add(stack.pop() / num); break; default: continue; } num = 0; sign = ch; } } int ans = 0; while (!stack.empty()) { ans += stack.pop(); } return ans; }