使用位运算符在 C++ 中乘以任何数字


在本教程中,我们将编写一个程序,使用位运算符将给定的两个数字相乘。

左移 (<<) 运算符用于乘法,而 右移 (>>) 运算符用于除法。

两个数字 x、y 的乘法可以写成 x * y = (x * 2) * (y / 2)(如果 y 为偶数),否则等于 x * y = (x * y) * (y / 2) + x。

因此,每当第二个数字变为奇数时,将第一个数字添加到结果中。让我们看看解决问题的步骤。

算法

  • 初始化两个数字。
  • 编写一个循环,直到第二个数字变为 0。
    • 如果第二个数字为奇数,则将第一个数字添加到结果中。
    • 将第一个数字左移 1 位。
    • 将第二个数字右移 1 位。

实现

以下是上述算法在 C++ 中的实现

Open Compiler
#include <bits/stdc++.h> using namespace std; int multiplyTwoNumbers(int a, int b) { int result = 0; while (b > 0) { if (b & 1) { result += a; } a = a << 1; b = b >> 1; } return result; } int main() { cout << multiplyTwoNumbers(75, 4) << endl; cout << multiplyTwoNumbers(90, 9) << endl; cout << multiplyTwoNumbers(83, 66) << endl; return 0; }

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

如果您运行以上代码,您将得到以下结果。

300
810
5478

更新于: 2021-10-25

10K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始
广告