call(back)
Algorithms & Data StructureseasySign in to star problems

Multiply Without *

Multiply two integers without *, /, ** or a multiplying helper, in O(log |b|) additions: multiply(a, b). Either may be negative or zero, and b fits in 32 bits.

multiply(6, 7)            // 42
multiply(-6, 7)           // -42
multiply(2147483647, 2)   // 4294967294

The tests can't see how you multiplied, so hold yourself to the rule.

Hints

Hint 1

Multiplication is repeated doubling: for every set bit of b, add the matching power-of-two multiple of a. Double a with n += n and halve b with a shift.

Hint 2

Work on absolute values and fix the sign at the end.

Asked at