## Facebook Interview Question

Software Engineers**Country:**United States

**Interview Type:**In-Person

Why make it more complex, this is clean, neat... and works.

```
def div_wo(a,b){
panic( b == 0 , 'Terrible parameter!')
printf('%d/%d%n', a,b)
sign_change = false
if ( a < 0 ){
sign_change = true
a = -a
}
if ( b < 0 ){
sign_change ^= true
b = -b
}
res = 0
while ( a >= b ){
res += 1
a -= b
}
sign_change ? -res : res
}
println( div_wo(0,1) )
println( div_wo(1,1) )
println( div_wo(1,2) )
println( div_wo(2,1) )
println( div_wo(2,-1) )
println( div_wo(-2,-1) )
println( div_wo(-2,1) )
println( div_wo(3,2) )
```

@NoOne: it's then just linear runtime O(dividend/divisor) whereas aone did actually place a logarithm in there (O(lg(dividend/divisor)).

1. terminology:

quotient = dividend / divisor

2. assumptions, constraints:

a) integer values (including signs)

b) positive and negative

c) since python, integers are 'unbound' no need to check overflow, but with Java or c++ you should check overflow, actually!

3. solution

1) turn the signs around until only positive integers remain

2) now do a 'high school division' on paper kind of thing in base 2, e.g.

1001001101 : 101 = (1 + 4 + 8 + 64 + 512) / 5

1111234567

1) 1001 / 101 = 1 remainder 100

2) 1000 / 101 = 1 remainder 11

3) 110 / 101 = 1 remainder 1

4) 11 / 101 = 0 remainder 11

5) 111 / 101 = 1 remainder 10

6) 100 / 101 = 0 remainder 100

7) 1001 / 100 = 1 remainder 100

= 1110101 Remainder 100

```
def division(dividend, divisor):
# division by zero case
if divisor == 0: raise ZeroDivisionError()
# turn signs to get rid of -dividend, -divisor
if dividend < 0: return -division(-dividend, divisor)
if divisor < 0: return -division(dividend, -divisor)
# sdiv = divisor * 2^n, sdiv > divisor and sdiv <= divisor * 2
sdiv = divisor
while sdiv < dividend:
sdiv <<= 1
# remove divisior * 2^i from dividend until divisor * 2^0
# therefore the quotient is multiplied by two in each iteration
quotient = 0
while sdiv >= divisor:
quotient <<= 1
if dividend >= sdiv:
dividend -= sdiv
quotient |= 1
sdiv >>= 1
return quotient
print(division(981, 12) == 81)
print(division(11, 12) == 0)
print(division(13, 13) == 1)
print(division(99191, 15) == 6612)
print(division(-1, 1) == -1)
print(division(1, -2) == 0)
print(division(2, -1) == -2)
print(division(-9, -3) == 3)
```

Looking for interview experience sharing and coaching?

Visit aonecode.com for private lessons by FB, Google and Uber engineers

ONE TO ONE real-time coaching offers

SYSTEM DESIGN Courses (highly recommended for candidates for FLAG & U)

ALGORITHMS (conquer DP, Greedy, Graph, Advanced Algos & Clean Coding),

latest interview questions sorted by companies,

mock interviews.

Our students got hired from G, U, FB, Amazon, LinkedIn and other top tier companies after weeks of training.

Feel free to email us aonecoding@gmail.com with any questions. Thanks!

- aonecoding July 15, 2017