public int calculate(String s) {
if (s == null || s.length() == 0) {
Stack<Integer> nums = new Stack();
Stack<Character> operators = new Stack();
if (Character.isDigit(c)) {
while ((i + 1) < n && Character.isDigit(s.charAt(i + 1))) {
num = 10 * num + s.charAt(i + 1) - '0';
else if (isOperator(c)) {
while (!operators.isEmpty() && hasPrecedence(c, operators.peek())) {
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
while (!operators.isEmpty() && operators.peek() != '(') {
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
while (!operators.isEmpty()) {
nums.push(calculate(operators.pop(), nums.pop(), nums.pop()));
return nums.isEmpty() ? 0 : nums.pop();
public boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
public int calculate(char operator, int num1, int num2) {
// check if op2 has higher precendence than op1
public boolean hasPrecedence(char op1, char op2) {
if (op2 == ')' || op2 == '(') {
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-')) {