Created
January 26, 2021 18:48
-
-
Save monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.
Revisions
-
monir-zaman created this gist
Jan 26, 2021 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,30 @@ 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()); } }