Divison without division operator

Viewed 126

I was trying to solve this question from leetcode:

Given two integers dividend and divisor, divide two integers without using multiplication, division, and mod operator. The integer division should truncate toward zero

My solution:

def divide(dividend, divisor):
    pseudo_count = 0 # pseudo-count
    flag = False # True if divisor or dividend is negative
    if dividend < 0:
        dividend = -dividend
        flag = True
    if divisor < 0:
        divisor = -divisor
        flag = True

    for i in range (0, dividend):
        pseudo_count += divisor
        if pseudo_count > dividend:
            if flag:
                return -i
            else:
                return i

    return -1

But divide(-10, -3) returns -3.

Can anyone spot the mistake here?

1 Answers

A minor change fixes your code.

  • Initialize the flag to False (no negative)
  • We flip the flag each time there is a negative
  • One negative sets the flag to True (one flip)
  • Two negatives sets the flag to False (two flips)

Code

def divide(dividend, divisor):
    pseudo_count = 0 # pseudo-count
    flag = False                # Initialize flag (no negatives)
    if dividend < 0:
        dividend = -dividend
        flag = not flag         # flip flag: 
                                # changes True to False and False to True
    if divisor < 0:
        divisor = -divisor
        flag = not flag         # flip flag:
                                # changes True to False and False to True

    # Note: two flips above solve the both negative issue
    for i in range (0, dividend):
        pseudo_count += divisor
        if pseudo_count > dividend:
            if flag:
                return -i
            else:
                return i

    return -1

divide(-10, -3)
# Output: 3
Related