Search code examples
javascriptalgorithmmathrpn

Explanation how should work the RPN calculator in the case of one argument and operand (divide or multiply)


I'm trying to understand how the RPN calculator should work in the case of the one argument and one operand, for example. divide or multiply.

I know how it should work in simple cases, eg.

> 1 
1
> 3
3
> +
result: 4  

explanation:  1 + 3 = 4

It's obvious how it works

The case 2 is harder but also pretty clear

7 2 3 * −
result: 1 
explanation:  7 - (2 * 3) = 1

So I know how it works basically.

I'm interested in these use cases.

4 -
result: -4

So in the case of a single argument, it should transform a number into a negative form. In the case of '+' we won't do anything

But how should it behave in these cases?

4 /

or

4 * 

Should I directly do a math operation with the same number? eg:

4 /   ===  4 / 4
4 *   ===  4 * 4

Thanks for any help!

P.S. Sorry for the stupid question but it's the first time when I faced this thing

UPDATE: Also, how about the use case when the user enters incorrect data. Eg. something like this?

1 + 3 - 5 * 3 /

By default, it ends the process or doesn't allow the user to continue to enter the incorrect data until the correct and valid argument be entered?


Solution

  • With RPN, you have usually some values in the registers/stack.

    As well as you get a CHS key for changing the sign.

    If you like to make an own calculator, you could specify the function as you want, as you like to take - as operator and for changing the sign.

    If you have only one value at the stack, you could omit binary operators and allow only unary operators.