返回介绍

lcci / 08.05.Recursive Mulitply / README_EN

发布于 2024-06-17 01:04:43 字数 3154 浏览 0 评论 0 收藏 0

08.05. Recursive Mulitply

中文文档

Description

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:

  1. The result will not overflow.

Solutions

Solution 1: Recursion + Bit Manipulation

First, we check if $B$ is $1$. If it is, we directly return $A$.

Otherwise, we check if $B$ is an odd number. If it is, we can right shift $B$ by one bit, then recursively call the function, and finally left shift the result by one bit and add $A$. If not, we can right shift $B$ by one bit, then recursively call the function, and finally left shift the result by one bit.

The time complexity is $O(\log n)$, and the space complexity is $O(\log n)$. Here, $n$ is the size of $B$.

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
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文