Integer division without using the / or * operator

后端 未结 7 538
梦如初夏
梦如初夏 2021-01-14 15:34

I am going through an algorithms and datastructures textbook and came accross this question:

1-28. Write a function to perform integer division withou

7条回答
  •  半阙折子戏
    2021-01-14 16:14

    This is not the fastest solution, but I think it's readable enough and works:

    def weird_div(dividend, divisor):
        if divisor == 0:
            return None
    
        dend = abs(dividend)
        dsor = abs(divisor)
        result = 0
        
        # This is the core algorithm, the rest is just for ensuring it works with negatives and 0
        while dend >= dsor:
            dend -= dsor
            result += 1
        
        # Let's handle negative numbers too
        if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
            return -result
        else:
            return result
    
    # Let's test it:
    print("49 divided by 7 is {}".format(weird_div(49,7)))
    print("100 divided by 7 is {} (Discards the remainder) ".format(weird_div(100,7)))
    print("-49 divided by 7 is {}".format(weird_div(-49,7)))     
    print("49 divided by -7 is {}".format(weird_div(49,-7)))   
    print("-49 divided by -7 is {}".format(weird_div(-49,-7)))   
    print("0 divided by 7 is {}".format(weird_div(0,7)))         
    print("49 divided by 0 is {}".format(weird_div(49,0)))
    

    It prints the following results:

    49 divided by 7 is 7
    100 divided by 7 is 14 (Discards the remainder) 
    -49 divided by 7 is -7
    49 divided by -7 is -7
    -49 divided by -7 is 7
    0 divided by 7 is 0
    49 divided by 0 is None
    

提交回复
热议问题