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.
Example 1:
Input: A = 1, B = 10 Output: 10
Example 2:
Input: A = 3, B = 4 Output: 12
Note:
- The result will not overflow.
function multiply(A: number, B: number): number {
if (A === 0 || B === 0) {
return 0;
}
const [max, min] = [Math.max(A, B), Math.min(A, B)];
return max + multiply(max, min - 1);
}
function multiply(A: number, B: number): number {
const max = Math.max(A, B);
const min = Math.min(A, B);
const helper = (a: number, b: number) =>
(b & 1 ? a : 0) + (b > 1 ? helper(a + a, b >> 1) : 0);
return helper(max, min);
}
impl Solution {
pub fn multiply(a: i32, b: i32) -> i32 {
if a == 0 || b == 0 {
return 0;
}
a.max(b) + Self::multiply(a.max(b), a.min(b) - 1)
}
}