4 lines in Ruby


  • 1

    Three slightly different solutions. I use a.fdiv(b) (followed later by .to_i) instead of a/b because Ruby rounds down, not towards zero, so at least one of the OJ's test cases is wrong for Ruby. As a nice side effect, Ruby doesn't complain about dividing by zero, so I can always calculate all four operations and pick the right result. Which looks rather neat, I think.

    def eval_rpn(tokens)
        t = tokens.pop    
        return t.to_i if !(op = '+-*/'.index t)
        b, a = eval_rpn(tokens), eval_rpn(tokens)
        [a+b, a-b, a*b, a.fdiv(b)][op].to_i
    end
    

    Or with t.match /\d/:

    def eval_rpn(tokens)
        t = tokens.pop    
        return t.to_i if t.match /\d/
        b, a = eval_rpn(tokens), eval_rpn(tokens)
        [a+b, a-b, a*b, a.fdiv(b)]['+-*/'.index t].to_i
    end
    

    Or with t.to_i.to_s == t:

    def eval_rpn(tokens)
        t = tokens.pop    
        return t.to_i if t.to_i.to_s == t
        b, a = eval_rpn(tokens), eval_rpn(tokens)
        [a+b, a-b, a*b, a.fdiv(b)]['+-*/'.index t].to_i
    end

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.