프로그래밍/알고리즘

계산기(stack)

프리월드 2017. 2. 24. 21:00


public void testCalculator() {
    String[] tokens = new String[]{"2""1""+""3""*"};
    //String[] tokens = new String[]{"4", "13", "5", "/", "+"};
    calculator(tokens);
}

public void calculator(String[] data) {
    Stack<String> stack = new Stack();
    for (String str : data) {
        switch (str) {
            case "+":
            case "*":
            case "/":
            case "-":
                int a = Integer.parseInt(stack.pop());
                int b = Integer.parseInt(stack.pop());
                if (str.equals("+"))
                    stack.push(String.valueOf(b + a));
                else if (str.equals("*"))
                    stack.push(String.valueOf(b * a));
                else if (str.equals("/"))
                    stack.push(String.valueOf(b / a));
                else if (str.equals("-"))
                    stack.push(String.valueOf(b - a));
                break;
            default:
                stack.push(str);
                break;
        }
    }
}

'프로그래밍 > 알고리즘' 카테고리의 다른 글

Stack(TwoStack)  (0) 2017.02.24
Stack(getMin)  (0) 2017.02.24
문자열 rotate 체크  (0) 2017.02.24
문자열 치환  (0) 2017.02.24
mergeSort  (0) 2017.02.24