Calculator

224. Basic Calculator

a + - ( )

227. Basic Calculator II

a - * /

772. Basic Calculator III

a + - * / ( )

有()就要有stack 有*/就要有2個num, 2個operator

5個if condition 1. 計算數字 2. ( num跟op歸零 3. ) 計算當前num, 在計算新n2 4. + or -, 計算新n1, 更新o1, o2 and n2 歸零 5. * or / 更新o2

return n1+o1*n2

public int calculate(String s) {
    int l1 = 0, o1 = 1;
    int l2 = 1, o2 = 1;
    Stack<Integer> stack = new Stack<>();

    for(int i=0; i<s.length(); i++){
        char c = s.charAt(i);
        if(Character.isDigit(c)){
            int num = c - '0';
            while(i+1 < s.length() && Character.isDigit(s.charAt(i+1)))
                num = num*10 + s.charAt(++i) - '0';
            l2 = (o2 == 1 ? l2*num : l2/num); 

        }else if(c == '('){
            // preserve l1, o1, l2, o2
            stack.push(l1);
            stack.push(o1);
            stack.push(l2);
            stack.push(o2);

            l1 = 0; o1 = 1;
            l2 = 1; o2 = 1;

        }else if(c == ')'){
            // caculate current num
            int num = l1 + o1*l2;

            // get old status;
            o2 = stack.pop();
            l2 = stack.pop();
            o1 = stack.pop();
            l1 = stack.pop();

            // 如果 '(' 之前不是 '*' '/' 這邊沒有作用
            l2 = (o2 == 1 ? l2*num : l2/num);

        }else if(c == '*' || c == '/'){
            o2 = c == '*' ? 1 : -1;

        }else if(c == '+' || c == '-'){
            l1 = l1 + o1*l2;
            o1 = c == '+'? 1 : -1;
            l2 = 1;
            o2 = 1;
        }
    }
    return l1 + o1*l2;
}

Last updated