comments | difficulty | edit_url |
---|---|---|
true |
中等 |
递归乘法。 写一个递归函数,不使用 * 运算符, 实现两个正整数的相乘。可以使用加号、减号、位移,但要吝啬一些。
示例1:
输入:A = 1, B = 10 输出:10
示例2:
输入:A = 3, B = 4 输出:12
提示:
- 保证乘法范围不会溢出
我们先判断
否则,我们判断
时间复杂度
class Solution:
def multiply(self, A: int, B: int) -> int:
if B == 1:
return A
if B & 1:
return (self.multiply(A, B >> 1) << 1) + A
return self.multiply(A, B >> 1) << 1
class Solution {
public int multiply(int A, int B) {
if (B == 1) {
return A;
}
if ((B & 1) == 1) {
return (multiply(A, B >> 1) << 1) + A;
}
return multiply(A, B >> 1) << 1;
}
}
class Solution {
public:
int multiply(int A, int B) {
if (B == 1) {
return A;
}
if ((B & 1) == 1) {
return (multiply(A, B >> 1) << 1) + A;
}
return multiply(A, B >> 1) << 1;
}
};
func multiply(A int, B int) int {
if B == 1 {
return A
}
if B&1 == 1 {
return (multiply(A, B>>1) << 1) + A
}
return multiply(A, B>>1) << 1
}
function multiply(A: number, B: number): number {
if (B === 1) {
return A;
}
if ((B & 1) === 1) {
return (multiply(A, B >> 1) << 1) + A;
}
return multiply(A, B >> 1) << 1;
}
impl Solution {
pub fn multiply(a: i32, b: i32) -> i32 {
if b == 1 {
return a;
}
if (b & 1) == 1 {
return (Self::multiply(a, b >> 1) << 1) + a;
}
Self::multiply(a, b >> 1) << 1
}
}
class Solution {
func multiply(_ A: Int, _ B: Int) -> Int {
if B == 1 {
return A
}
if (B & 1) == 1 {
return (multiply(A, B >> 1) << 1) + A
}
return multiply(A, B >> 1) << 1
}
}