在 C++ 中计算将 1 加到给定数字 N 后发生变化的位数
假设我们给定一个数字,例如 num,任务是计算将 1 加到该数字后发生变化的位总数。
数字的二进制表示是将给定数字转换为 0 和 1 的形式,可以通过多种方法实现。其中一种方法是计算给定数字与 2 的最小公倍数,如果余数不为 0,则将该位设置为 1,否则设置为 0。
位的加法表如下:
0 + 1 = 1 1 + 0 = 1 0 + 0 = 0 1 + 1 = 1 ( 1 bit carry)
例如
Input − num = 10 Output − count is : 1
解释 - 10 的二进制表示为 1010,当加 1 后,表示变为 1011。很明显,只有一位发生了变化,因此计数为 1。
Input − num = 5 Output − count is : 2
解释 - 5 的二进制表示为 101,当加 1 后,表示变为 110。很明显,两位发生了变化,因此计数为 2
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
下面程序中使用的方案如下:
输入整数类型的数字,例如 int num
声明一个变量来存储计数,例如 int count
再取一个变量,例如 temp,计算 num 的异或,并将其设置为 n ^ (n + 1)
在 count 变量中调用 __builtin_popcount(temp)。此函数用于计算给定整数二进制表示中数字的计数。它是 GCC 编译器的内置函数。
返回计数
打印结果。
示例
#include <iostream> using namespace std; // Function to find number of changed bit int changedbit(int n){ int XOR = n ^ (n + 1); // Count set bits in xor value int count = __builtin_popcount(XOR); return count; } int main(){ int n = 10; cout <<"count is: " <<changedbit(n); return 0; }
输出
如果我们运行以上代码,我们将得到以下输出:
count is: 1
广告