Created
January 26, 2021 18:48
-
-
Save monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.
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
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