Interview Question: Simple Division


I will start collecting some interview questions.

Q: Implement a Division but cannot use the division operator ‘/’ on two integers.

A: We can use substraction instead. However, we need to check the signs on both integers. The Python code is presented.

#!/usr/bin/env python
# https://helloacm.com

class DivError(Exception):# customize exception
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return 'Divide by Zero: ' + repr(self.value)

def div(a, b):
    if b == 0:
        raise DivError(a)  # rasie Exception
    else:
        sgn = a * b > 0
        a = abs(a)
        b = abs(b)
        c = 0
        while a >= b: # repeative substraction 
            a -= b
            c += 1
        return c if sgn > 0 else -c # check sign

if __name__ == "__main__":
    print div(128, 5)
    print div(-119, 3)
    print div(99, 3)
    print div(-60, -21)
    print div(2, 0)

The above prints the following:

25
-39
33
2

Traceback (most recent call last):
  File "C:/Python27/test.py", line 32, in <module>
    print div(2, 0)
  File "C:/Python27/test.py", line 13, in div
    raise DivError(a)
DivError: Divide by Zero: 2
</module>

The idea is to substract b from a until zero is reached. This is the answer of the integer part a / b . However, be careful to take care with the signs. A customized exception will be thrown out when the value of b is zero.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
267 words
Last Post: Large Address Aware
Next Post: Interview Question: How to Check Integer is the Power of Two?

The Permanent URL is: Interview Question: Simple Division

Leave a Reply