Basic Calculator test case input "1+2*5/3+6/4*2" expects a wrong answer of 6 instead of 5


  • 0
    D

    I think one of the test case is wrong. The input of "1+2 5/3+6/42" was used. My code gave a result of 5 but the test expects a result of 6. if you evaluate the expression the right answer should actually be 5 as my code returned. The evaluation of the expression is as follows

    1+2 *5/3+6/4*2        = 1+2*1+6/4*2      (ie 5/3 = 1)
                          = 1+2*1+1  *2      (ie 6/4 = 1)
                          = 1+2  +1  *2      (ie 2*1 = 2) 
                          = 1+2  +2          (ie 1*2 = 2)
                          = 5
    

    I do not understand why the code test was expecting an output of 6. Can anyone give a reason why the value 6 was expected as the result for the expression ?


  • 2

    Multiplication (*) or Division (/) should be evaluated in the order of left to right. Therefore,

     2 * 5 / 3
     = (2 * 5) / 3
     = 10 / 3
     = 3.
    

    It is equal to 3, not 2 that you originally calculated.


  • 0
    D
    This post is deleted!

  • 0
    D

    Ok that is true. I have always evaluated division before multiplication according to BODMAS. Thanks for the correction


  • 0

    Then you have always done it wrong. BODMAS ranks multiplication and division the same and you're supposed to go left to right. At least I just checked the top four Google results for "BODMAS" and every single one of them explicitly says so.


  • 0
    A
    1+2*5/3+6/4*2
    1+(2*5)/3+6/4*2
    1+(10/3)+6/4*2
    1+3+(6/4)*2
    1+3+(1*2)
    1+3+2
    6

Log in to reply
 

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