1、判断奇偶
一个数二进制的末位数是1,则该数是奇数,末位数是0,则该数是偶数。因此可以用 a&1 == 0来判断。
如下例:
#include <iostream>
using namespace std;
int main()
{
//输出0到100之间的所有奇数
for (int i = 0; i < 100; ++i)
{
if (i & 1)
{
cout << i << ' ';
}
}
cout << endl;
return 0;
}
2、消除尾一
Ⅰ、消除最后出现的1:x & (x - 1)
如:用 O(1) 时间检测整数 n 是否是 2 的幂次。
因为2的幂次满足① > 0,②二进制表示中只有一个1。因此,代码如下:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n > 0 && (n & (n-1) == 0))
{
cout << n << "是2的幂次" << endl;
}
else
{
cout << n << "不是2的幂次" << endl;
}
return 0;
}
再一个例子:计算在一个 32 位的整数的二进制表式中有多少个 1。
x&(x-1)消去x的最后出现的1个1,因此不断做x = x&(x-1)就可以得到,x的二进制表达式中有多少个1。代码如下:
#include <iostream>
using namespace std;
int main()
{
int x;
cin >> x;
int cnt = 0;
while (x != 0)
{
x = x & (x-1);
cnt += 1;
}
cout << cnt << endl;
return 0;
}
再如:如果要将整数A转换为B,需要改变多少个bit位?
这是对上面问题的拓展,也会用到异或的知识。如果我们将A^B,相同位为0,相异位为1,接下来的就很容易想到了 —— 统计A^B后1的个数!代码如下~:
#include <iostream>
using namespace std;
int main()
{
int A, B;
cin >> A >> B;
int num = A + B;
int cnt = 0;
while (num != 0)
{
num = num & (num-1);
cnt += 1;
}
cout << endl;
return 0;
}
Ⅱ、消除最末所有位的1:x & (x + 1)
如:(蓝桥杯2016省赛A5题):题目与题解见该链接https://blog.youkuaiyun.com/t11383/article/details/88081030
就先总结到这里啦~,之后遇到更有趣的继续总结!