Created
April 17, 2013 07:47
-
-
Save siong1987/5402499 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Calculator | |
def evaluate statement | |
symbols = statement.split(' ') | |
puts calculate(symbols) | |
end | |
def calculate symbols | |
if symbols.length == 1 | |
return symbols[0] | |
else | |
queue = [] | |
symbols.length.times do | |
symbol = symbols.shift | |
if symbol == '+' | |
result = queue.pop.to_i + queue.pop.to_i | |
queue << result | |
break | |
elsif symbol == '-' | |
result = queue.pop.to_i - queue.pop.to_i | |
queue << result | |
break | |
elsif symbol == '*' | |
result = queue.pop.to_i * queue.pop.to_i | |
queue << result | |
break | |
elsif symbol == '/' | |
result = queue.pop.to_i / queue.pop.to_i | |
queue << result | |
break | |
else | |
queue << symbol | |
end | |
end | |
queue.length.times do | |
symbols.unshift(queue.pop) | |
end | |
calculate(symbols) | |
end | |
end | |
end | |
c = Calculator.new | |
c.evaluate("70 10 4 + 5 * -") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment