1. 程式人生 > 實用技巧 >224. 基本計算器

224. 基本計算器

class Solution {
    int index = 0;
    public int calculate(String s) {
        int n = s.length();
        Stack<Integer> stack = new Stack();
        char pre = '+';
        int num = 0;
        for(; index < n; index ++) {
            char c = s.charAt(index);
            if(Character.isDigit(c)) {
                num 
= num * 10 + (c - '0'); } if(c == '(') { index++; num = calculate(s); } if(!Character.isDigit(c) && c != ' ' || index == n - 1) { switch(pre) { case '+': stack.push(num);
break; case '-': stack.push(-num); break; case '*': stack.push(stack.pop() * num); break; case '/': stack.push(stack.pop()
/ num); break; } pre = c; num = 0; } if(c == ')') break; } int res = 0; while(!stack.empty()) { res += stack.pop(); } return res; } }