16
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javaで逆ポーランド記法(計算編)

Last updated at Posted at 2013-11-11

AOJがJava1.7対応してないのしらなくて時間を無駄にしました。。。

今回は

#逆ポーランド記法で渡されたデータの計算

詳細は以下のリンクが分かりやすいです。
Wikipedia:逆ポーランド記法
※例もリンク先にあるので省略します。

1.6向けでStackを使っていますが、1.7以降はDequeの利用が推奨されています。

#解法
##Java1.6向け

package aoj;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;

public class ReversePolishNotationOld {

	public static void main(String args[]) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] stringArray = br.readLine().split("\\s");

		// 後に入れたものを先に抜き出す(いわゆるLIFO)
		Stack<Integer> que = new Stack<Integer>();
		int a = 0;
		int b = 0;
		for (int i = 0; i < stringArray.length; i++) {
			if (stringArray[i].equals("+")) {
				a = que.pop();
				b = que.pop();
				que.add(b + a);
				continue;
			}
			if (stringArray[i].equals("-")) {
				a = que.pop();
				b = que.pop();
				que.add(b - a);
				continue;
			}
			if (stringArray[i].equals("*")) {
				a = que.pop();
				b = que.pop();
				que.add(b * a);
				continue;
			}
			if (stringArray[i].equals("/")) {
				a = que.pop();
				b = que.pop();
				que.add(b / a);
				continue;
			}
			// 演算子以外はstackに登録する
			que.push(Integer.parseInt(stringArray[i]));
		}
		System.out.println(que.pop());
	}
}

##Java1.7向け

package aoj;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;

public class ReversePolishNotationNew {
	public static void main(String args[]) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] stringArray = br.readLine().split("\\s");

		Deque<Integer> que = new ArrayDeque<>();
		int a = 0;
		int b = 0;
		for (int i = 0; i < stringArray.length; i++) {
			switch (stringArray[i]) {
			case "+":
				a = que.pollFirst();
				b = que.pollFirst();
				que.addFirst(b + a);
				break;
			case "-":
				a = que.pollFirst();
				b = que.pollFirst();
				que.addFirst(b - a);
				break;
			case "/":
				a = que.pollFirst();
				b = que.pollFirst();
				que.addFirst(b / a);
				break;
			case "*":
				a = que.pollFirst();
				b = que.pollFirst();
				que.addFirst(b * a);
				break;
			default:
				que.addFirst(Integer.parseInt(stringArray[i]));
			}
		}
		System.out.println(que.pop());
	}
}
16
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?