Created
June 26, 2011 09:27
-
-
Save zaki50/1047442 to your computer and use it in GitHub Desktop.
Main.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.zakky.rpn; | |
import java.io.BufferedReader; | |
import java.io.InputStreamReader; | |
import java.util.Stack; | |
import java.util.concurrent.TimeUnit; | |
public class Main { | |
public static void main(String[] args) throws Exception { | |
final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); | |
String line = reader.readLine(); | |
final Stack<Long> s = new Stack<Long>(); | |
final String[] inputs = line.split(" +"); | |
printStack(s); | |
for (String input : inputs) { | |
System.out.println("input is " + input); | |
if (Character.isDigit(input.charAt(0))) { | |
s.push(Long.valueOf(input)); | |
System.out.println("pushed " + input); | |
} else if (input.charAt(0) == '+') { | |
final long v2 = s.pop(); | |
System.out.println("poped " + v2); | |
final long v1 = s.pop(); | |
System.out.println("poped " + v1); | |
s.push(v1 + v2); | |
System.out.println("pushed " + v1 + " + " + v2); | |
} else if (input.charAt(0) == '-') { | |
final long v2 = s.pop(); | |
System.out.println("poped " + v2); | |
final long v1 = s.pop(); | |
System.out.println("poped " + v1); | |
s.push(v1 - v2); | |
System.out.println("pushed " + v1 + " - " + v2); | |
} else if (input.charAt(0) == '*') { | |
final long v2 = s.pop(); | |
System.out.println("poped " + v2); | |
final long v1 = s.pop(); | |
System.out.println("poped " + v1); | |
s.push(v1 * v2); | |
System.out.println("pushed " + v1 + " * " + v2); | |
} else if (input.charAt(0) == '/') { | |
final long v2 = s.pop(); | |
System.out.println("poped " + v2); | |
final long v1 = s.pop(); | |
System.out.println("poped " + v1); | |
s.push(v1 / v2); | |
System.out.println("pushed " + v1 + " / " + v2); | |
} | |
printStack(s); | |
} | |
System.out.println((s.size() == 1) ? ("The answer is " + s.pop()) | |
: ("invalid RPN expression: " + line)); | |
} | |
private static void printStack(Stack<?> s) { | |
final StringBuilder sb = new StringBuilder("stack = ["); | |
for (int i = s.size() - 1; 0 <= i; i--) { | |
sb.append(s.get(i)); | |
sb.append(","); | |
} | |
if (!s.isEmpty()) { | |
sb.setLength(sb.length() - ",".length()); | |
} | |
sb.append("]"); | |
System.out.println(sb.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment