Multiply two numbers without the multiplication operator
Coding problemEasy-MediumAsked in: Accenture
Given two integers a and b, return their product. Do not use the multiplication operator; addition, subtraction and bit shifts are allowed. (Shifting a number left by one bit doubles it; shifting right by one bit halves it and drops the remainder.)
Either number may be negative or 0. The numbers can be very large (see the constraints), so adding a to itself b times is far too slow. Both numbers and the product fit in a 64-bit integer.
Examples
Example 1
Input: a = 6, b = 7
Output: 42
Example 2
Input: a = -3, b = 4
Output: -12
Example 3
Input: a = 2147483647, b = 2
Output: 4294967294
The product does not fit in 32 bits.
Constraints
- a, b and the product a times b are all between -4,000,000,000,000,000,000 and 4,000,000,000,000,000,000
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.