import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Stack;
import java.util.StringTokenizer;
class Solution {
static HashMap<Character, Integer> priority = new HashMap<Character, Integer>();
public static void main(String args[]) throws Exception {
priority.put('+', 1);
priority.put('*', 2);
priority.put('(', 0);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
for (int testCase = 1; testCase <= 10; testCase++) {
StringTokenizer st = new StringTokenizer(br.readLine(), "");
st.nextToken();
st = new StringTokenizer(br.readLine(), "");
char[] infix = st.nextToken().toCharArray();
System.out.printf("#%d %d\n", testCase, calculate(infixToPostfix(infix)));
}
}
public static String infixToPostfix(char[] infix) {
String formula = "";
Stack<Character> stack = new Stack<>();
for (char token : infix) {
if (Character.isDigit(token)) {
formula += token;
}
else if (token == '(') {
stack.add(token);
} else if (token == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
formula += stack.pop();
}
stack.pop();
} else {
while (!stack.isEmpty() && priority.get(stack.peek()) >= priority.get(token)) {
formula += stack.pop();
}
stack.push(token);
}
}
while(!stack.isEmpty()) {
formula += stack.pop();
}
return formula;
}
public static int calculate(String postfix) {
char[] formula = postfix.toCharArray();
Stack<Integer> stack = new Stack<>();
for (char token : formula) {
if (Character.isDigit(token)) {
stack.push(Character.getNumericValue(token));
}
else {
int x = stack.pop();
int y = stack.pop();
if (token == '+') {
stack.push(x + y);
}
else if (token == '*') {
stack.push(x * y);
}
}
}
return stack.pop();
}
}
계산기1 코드로 해결하였다.
Link : https://velog.io/@kwonsc/SWEA-1222-%EA%B3%84%EC%82%B0%EA%B8%B01