Skip to content

Instantly share code, notes, and snippets.

@monir-zaman
Created January 26, 2021 18:48
Show Gist options
  • Select an option

  • Save monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.

Select an option

Save monir-zaman/356c34a46522898e937b09a87353cd6a to your computer and use it in GitHub Desktop.

Revisions

  1. monir-zaman created this gist Jan 26, 2021.
    30 changes: 30 additions & 0 deletions PolishNotation.java
    Original 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());
    }
    }