Skip to content

Instantly share code, notes, and snippets.

@monir-zaman
Created January 26, 2021 18:48
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 monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.
Save monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class PolishNotation { // also known as prefix notation
public static void main(String[] args)
{ // * / 12 3 25
String[] input = {"*","/", "12", "3", "25"}; // * ( 12 / 3 ) 25
System.out.println(getPolishSum(input)); // ( 12 / 3 ) * 25
} // 100
private static long getPolishSum(String[] input) {
Stack<String> digitsStack = new Stack<String>();
for (int i =input.length-1; i > -1; i--) {
if (input[i].equals("+") ||
input[i].equals("-") ||
input[i].equals("*") ||
input[i].equals("/") ) {
long firstValue = Long.valueOf(digitsStack.pop());
long secondValue = Long.valueOf(digitsStack.pop());
long temp = 0;
if (input[i].equals("+")) temp = firstValue + secondValue;
else if (input[i].equals("-")) temp = firstValue - secondValue;
else if (input[i].equals("*")) temp = firstValue * secondValue;
else if (input[i].equals("/")) temp = firstValue / secondValue;
digitsStack.push(String.valueOf(temp));
}
else digitsStack.push(input[i]);
}
return Long.valueOf(digitsStack.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment