Skip to content

Instantly share code, notes, and snippets.

@zaki50
Created June 26, 2011 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaki50/1047310 to your computer and use it in GitHub Desktop.
Save zaki50/1047310 to your computer and use it in GitHub Desktop.
Main.java
package org.zakky.rpn;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
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(" +");
for (String input : inputs) {
if (Character.isDigit(input.charAt(0))) {
s.push(Long.valueOf(input));
} else if (input.charAt(0) == '+') {
s.push(s.pop() + s.pop());
} else if (input.charAt(0) == '-') {
long v2 = s.pop();
long v1 = s.pop();
s.push(v1 - v2);
} else if (input.charAt(0) == '*') {
s.push(s.pop() * s.pop());
} else if (input.charAt(0) == '/') {
long v2 = s.pop();
long v1 = s.pop();
s.push(v1 / v2);
}
}
System.out.println((s.size() == 1) ? ("The answer is: " + s.pop())
: ("invalid RPN expression: " + line));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment