SWEA 1223計算機2



これはスタック演算を用いて与えられた計算式を演算することを要求する問題である.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Stack;
import java.util.StringTokenizer;

public class Solution {
	static BufferedReader br;
	static BufferedWriter bw;
	static StringTokenizer st;

	// 3+4+5*6+7
	// 3 4 + 5 6
	// + *
	public static void main(String[] args) throws IOException {
		br = new BufferedReader(new InputStreamReader(System.in));
		bw = new BufferedWriter(new OutputStreamWriter(System.out));

		for (int test_case = 1; test_case <= 10; test_case++) {
			StringBuilder sb = new StringBuilder();
			Stack<Character> s = new Stack<>();
			
			int N = Integer.parseInt(br.readLine());
			st = new StringTokenizer(br.readLine());
			char[] tmp = st.nextToken().toCharArray();


			for (int i = 0; i < N; i++) {
				if (tmp[i] == '+' || tmp[i] == '*') {
					if (s.isEmpty())
						s.add(tmp[i]);
					else if (tmp[i] == '+') {
						while (!s.isEmpty()) {
							sb.append(s.pop());
						}
						s.add(tmp[i]);
					} else {
						if (s.peek().equals("*")) {
							while (s.isEmpty() || s.peek().equals("+")) {
								sb.append(s.pop());
							}
							s.add(tmp[i]);
						} else {
							s.add(tmp[i]);
						}
					}
				} else {
					sb.append(tmp[i]);
				}
			}
			while (!s.isEmpty()) {
				sb.append(s.pop());
			}
			tmp = sb.toString().toCharArray();

			Stack<String> output = new Stack<>();
			for (int i = 0; i < N; i++) {
				if (tmp[i] != '+' && tmp[i] != '*') {
					output.add(Character.toString(tmp[i]));
				} else {
					if (tmp[i] == '+') {
						int t = Integer.parseInt(output.pop()) + Integer.parseInt(output.pop());
						output.add(Integer.toString(t));
					} else if (tmp[i] == '*') {
						int t = Integer.parseInt(output.pop()) * Integer.parseInt(output.pop());
						output.add(Integer.toString(t));
					}
				}
			}
			bw.append("#" + test_case + " " + output.pop() + "\n");
		}
		bw.flush();
		bw.close();
	}
}