Hello, How can I calculate the exprs in the uploaded pic to get the output.
The idea is taking the operator to calculate the numbers before.
The expressions are what I refer to as RPN or Reverse Polish Notation.
In the first case it is 2 + 3 which is pretty straight forward so if you were using a swift playground you would code that as
let output = 2 + 3
print(output)
and you should see 5 printed in the console.
The second expression is pretty straight forward too.
Don’t forget the order in which math operations are done BEMDAS (Brackets, Exponential, Multiplication, Division, Addition, Subtraction)
Expresions 3 and 4 are tricky but if you are familiar with an RPN calculator you should be able to figure out how to write a swift expression to achieve the result.
If you can’t figure it out then let me know and I’ll provide you with a solution.
Thank you for your response. I tried to solve it, but my solution is not correct. The point is to write a function to deal with this kind of expressions. One function takes the expressions as a String input and return the solution as an Int.
Ah, now that puts a completely different light on the requirement compared to what you posted initially.
Yes! I’m sorry, it supposed to be explained more
This algorithm works nicely:
What you need to do is put the expression in an array. For example take the first one:
let expression1 = ["2", "3", "+"]
Paste the code from Github into your playground (or project).
Declare an instance of that class, ie:
let evaluate = EvaluateReversePolishNotation()
then call the function and assign the output to a variable like this:
let result = evaluate.evalRPN(expression1)
then print the result to the console:
print(result)
For the example above you should see 5 printed in the console.
Fantastic, Thank you.
If you wanted to you could change all the Int
references to Double
in that class and it will work with floating point values.