移位运算符如何在查找两个整数中的不同位数?
How shifting operator works in finding number of different bit in two integer?
我试图找出两个数字中不同位的数量。 我在这里找到了一个解决方案,但无法理解它是如何 works.it 随着我和做和1正确移动的。 其实背后发生了什么?为什么要循环穿越32?
void solve(int A, int B)
{
int count = 0;
// since, the numbers are less than 2^31
// run the loop from '0' to '31' only
for (int i = 0; i < 32; i++) {
// right shift both the numbers by 'i' and
// check if the bit at the 0th position is different
if (((A >> i) & 1) != ((B >> i) & 1)) {
count++;
}
}
cout << "Number of different bits : " << count << endl;
}
循环从 0 到 31(不是到 32(运行,因为这些是构成 32 位整数的所有可能位,我们需要检查它们。
在循环中,代码
if (((A >> i) & 1) != ((B >> i) & 1)) {
count++;
}
工作原理是将两个整数中的每一个向右移动i
(如果i > 0
则切断位(,在移位后提取最右边的位(& 1
(并检查它们是否相同(即都是 0 或两个 1(。
让我们通过一个例子:solve(243, 2182)
.在二进制中:
243 = 11110011
2182 = 100010000110
diff bits = ^ ^^^ ^ ^
int bits = 00000000000000000000000000000000
i = 31 0
<-- loop direction
产生差异的i
指数为 0、2、4、5、6 和 11(我们从右到左检查 - 在第一次迭代中,i = 0
,没有任何偏移,所以& 1
给了我们最右边的位,等等(。在上面的示例中,每个数字左侧的填充都是 0。
另外,请注意,有更好的方法可以在没有循环的情况下做到这一点:获取两个数字的 XOR 并对它们运行popcount
(计算设置的位数(:
__builtin_popcount(243 ^ 2182); // => 6
或者,更便携:
std::bitset<CHAR_BIT * sizeof(int)>(243 ^ 2182).count()
另一个注意事项:最好避免using namespace std;
,返回一个值而不是产生打印副作用,并为该方法提供一个比solve
更清晰的名称,例如bit_diff
(我意识到这是来自极客forgeeks(。
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 比较C++中两个整数的最有效和最干净的方法是什么?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 为什么将两个浮点数相加会得到一个整数C++?
- 从两个 4x64 位整数数组中获取取模
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 比较两个整数在C++中与未知 int 类型的相等性
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 如何组合两个整数向量
- 在两个整数之间交换最右边的N位
- 打印出两个整数之间的偶数
- 为什么将两个总和为 32k >整数相加时得到负数?
- C++ 两个线程,共享几个整数变量
- Python 等效代码,可像C++一样直接附加两个整数
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- 移位运算符如何在查找两个整数中的不同位数?
- 如何安全地比较两个无符号整数计数器?
- 添加两个二进制数(整数数组)
- 运算符"|"如何计算两个整数?
- 如何找出在两个整数的乘积中设置了多少位(等于 1)