Use python can't pass the test


  • 0
    A
    class Solution:
    # @param tokens, a list of string
    # @return an integer
    def evalRPN(self, tokens):
        stack = []
        for token in tokens:
            if token == "+":
                rhs = float(stack.pop())
                lhs = float(stack.pop())
                stack.append(lhs + rhs)
                continue
            if token == "-":
                rhs = float(stack.pop())
                lhs = float(stack.pop())
                stack.append(lhs - rhs)
                continue
            if token == "*":
                rhs = float(stack.pop())
                lhs = float(stack.pop())
                stack.append(lhs * rhs)
                continue
            if token == "/":
                rhs = float(stack.pop())
                lhs = float(stack.pop())
                stack.append(lhs / rhs)
                continue
            stack.append(token)
        return int(float(stack.pop()))
    

    I thing it's because rounding problem 16.54545454 + 5 ==> 21 but the answer is 22


  • 0
    S

    IMO, 16.5454 + 5 = 21 in everything language. Could you share the test case you failed?

    Anyway, here is a post would be helpful.


  • 0
    J

    why don't just use integer arithmetic?


  • 0
    A

    because the input is string
    and divide could be a decimal value, I thought it's better to round at the last step

    Input: ["10","6","9","3","+","-11","","/","","17","+","5","+"]
    Output: 21
    Expected: 22


  • 1
    A

    thank you Shangrila for your reply, which confused me is
    Input: ["4","13","5","/","+"] ==> 13/5+4 = 6.6
    Output: 7
    Expected: 6

    Input: ["10","6","9","3","+","-11","","/","","17","+","5","+"] ==> 21.54545460
    Output: 21
    Expected: 22

    the first example didn't go up to 7 but the second go up to 22, any idea?


  • 0
    A

    James, you are right, it was cast to int when it do devide, int this case, 6 / (9+3)*-11 is zero, so the result is 17 + 5 = 22
    Thanks


  • 0
    A

    it was cast to int when it do devide, in this case, 6 / (9+3)*-11 is zero, so the result is 17 + 5 = 22 Thanks


Log in to reply
 

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