javacalculatorpostfix-notation

how to add together the values ​from the RPN algorithm


I’m writing calculator that calculates values ​​from expressions:

3+(23/24)*34/24

I used RPN algorithm: https://en.wikipedia.org/wiki/Reverse_Polish_notation

I have now sorted expression in String:

3 23 24 / 34 * 24 / +

I don't have any idea how can I get value from this expression.

Thx


Solution

  • The basic algorithm is based on a stack-like structure

    For each token in the expression:

    E.g.:

    "3 23 24 / 34 * 24 / +"
                                                 Stack
    3:  push 3                                   |   3
    23: push 23                                  |   3    23
    24: push 24                                  |   3    23     24
    /:  pop (24),   pop (23),    push 23/24      |   3     0.95
    34: push 34                                  |   3     0.95  34
    *:  pop (34),   pop (0.95),  push 0.95*34    |   3    32.58
    24: push 24                                  |   3    32.58  24
    /:  pop (24),   pop (32.58), push 32.58/24   |   3     1.35
    +:  pop (1.35), pop (3),     push 3+1.35     |   4.35
    

    The last value that remains in the stack is the result