Should this one return -1 or 0 1004958205, -2137325331


  • 0
    Y

    my answer is -1, but it's expecting 0

    print 1004958205/-2137325331
    -1


  • 0
    R

    try a simpler input:

    print 1/-2
    >> -1
    print -1/2
    >> -1
    

    Python seems to use the floor function. This works well for positive integers (i.e. 1/2 = floor(0.5) = 0), but not what you expect for negative results (-1/2 = floor(-0.5) = -1). What I do is preserve the sign of the product and treat numerator and divisor as positive ints:

    def betterDiv(num, den):
        sign = 1 if num * den >= 0 else -1
        return sign * (abs(num)/abs(den))
    
    betterDiv(1, -2)
    >> 0

Log in to reply
 

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