euisblue
150. Evaluate Reverse Polish Notation

Ruby

1# @param {String[]} tokens 2# @return {Integer} 3class String 4 def is_num 5 !!match(/^([-]?)[0-9]+$/) 6 end 7end 8 9def eval_rpn(tokens) 10 op = [] 11 tokens.each do |t| 12 if t.is_num 13 op.push(t.to_i) 14 else 15 a = op.pop 16 b = op.pop 17 if t == "+" 18 op.push(a+b) 19 elsif t == "-" 20 op.push(b-a) 21 elsif t == "*" 22 op.push(a*b) 23 elsif t == "/" 24 op.push((b/a.to_f).to_i) 25 end 26 end 27 end 28 op.pop 29end