I came up with this solution for the following question from "Cracking the coding interview" I think it's faster and more elegant from what I saw in their solution but not sure it works on all cases. Can anyone tell if there is some edge case I've missed?
The original question from CTCI is(Question 8.5 on recursion and dynamic programming):
Write a recursive function to multiply two positive integers without using the * operator. You can use addition, subtraction, and bit shifting, but you should minimize the number of those operations.
My solution is:
def foo(a, b, mult = 0):
if a == 0 or b == 0:
return 0
if (a & 1) == 1:
return (b << mult) + foo(a >> 1, b, mult + 1)
return foo(a >> 1, b, mult + 1)
Can anyone tell if I've missed something?