-
-
Save zaki50/1047310 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; | |
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