Skip to content

Instantly share code, notes, and snippets.

@kexline4710
Created February 16, 2014 19:29
Show Gist options
  • Save kexline4710/9039373 to your computer and use it in GitHub Desktop.
Save kexline4710/9039373 to your computer and use it in GitHub Desktop.
My solution to the Reverse Polish Notation Problem
class RPNCalculator
def evaluate(rpn_string)
rpn_arr = rpn_string.split(' ')
operating_arr = []
rpn_arr.each do |element|
operating_arr << case element
when /\d+/ then element.to_i
when '+' then operating_arr.pop + operating_arr.pop
when '*' then operating_arr.pop * operating_arr.pop
when '-' then - operating_arr.pop + operating_arr.pop
end
end
operating_arr.last
end
end
calc = RPNCalculator.new
p calc.evaluate('1 2 +') # => 3
p calc.evaluate('2 5 *') # => 10
p calc.evaluate('50 20 -') # => 30
# The general rule is that 'A B op' is the same as 'A op B'
# i.e., 5 4 - is 5 - 4.
p calc.evaluate('70 10 4 + 5 * -') # => 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment