Search code examples
infix-notationpostfix-mtainfix-operator

Infix to postfix for negative numbers


How do I convert negative numbers from infix to postfix ?

Suppose I have a expression

a = - b - (-c-d)

In some places I read that you can parathesize the negative numbers like

a = (-b) - (-c-d)

But here if I do that, I will get a term like "ab-" at the beginning of the postfix expression which means a-b and is incorrect.

How do I convert this ?


Solution

  • In infix notation, you must distinguish between the binary subtraction operator sub and the unary negation operator neg. Both are represented by a minus sign, but the context tells you which is which.

    You've got a negation, when the minus as at the beginning of the expression, or after an opening parenthesis or after a binary operator:

        − (x + y)   →   x y add neg
        4 × − x   →   4 x neg mult
        2 × (− x + y)   →   2 x neg y add mult

    You've got a subtraction when the minus is after a closing parenthesis or after a symbol, i.e. after a variable or number:

        1 − x   →   1 x sub
        (4 ∗ x) − 1   →   4 x mult 1 sub

    Take care that the unary operator neg just takes one argument off the stack. If you want to stick with binary operators, you can push a zero before the second operand and use binary sub:

        − (x + y)   →   0 x y add sub
        4 x neg mult   →  4 0 x sub mult
        2 x neg y add mult   →   2 0 x sub y add mult

    Finally, you can apply a similar logic to unary plus, which you can just ignore:

        + x   →   x
        + (x + y)   →   x y add