I thought about a calculator algorithm that can perform + (addition),-(subtraction), * (multiplication),/(division) with ruby. The most famous way to make a calculator algorithm is (1) Receive the given formula → (2) Convert to reverse Polish notation → (3) Calculate and return the calculation result. This time, I will introduce my own way of thinking from ② to ③. As a matter of fact, I am a beginner myself, so please point out any mistakes.
input = gets.chomp.split(" ")
operator = ['+','-','*','/']
num_stack = []
input.each do |s|
#If you get a number, put it on the stack (using a regular expression).
if s =~ /[0-9]/
num_stack << s
end
#If an operator comes, take two numbers from the stack and calculate according to each operator.
if operator.include?(s)
a = num_stack.pop
b = num_stack.pop
a = a.to_i
b = b.to_i
case s
when '+'
num_stack << b + a
when '-'
num_stack << b - a
when '*'
num_stack << b * a
when '/'
num_stack << b / a
end
end
end
ans = num_stack.pop
puts ans
Recommended Posts