位运算的二三栗子
一:判断整数的奇偶性
偶数:(2N) & 1 = 0;
奇数:(2N-1) & 1 = 1;
整数特性:
奇数二进制最低位是1;
偶数二进制最低位是0;
二:
交换两个变量a, b的值
#include <iostream>
int main(int argc, char const *argv[])
{
int a = 5,b = 90;
a = a^b;
b = a^b;
a = a^b;
std::cout<<a<<" "<<b;
return 0;
}
----------------------------------------------
90 5
E:\Users\admin\Documents\VScode\Code>
==============================================
三:
消除数组中重复的整数a
使用特性
a ^ a = 0
a ^ 0 = a
==============================================
四:
判断整数的二进制中1的个数,当只有一个是1这个整数是2的整数次方
使用特性
1 & 1 = 1;
>>移动逐位比较
#include <iostream>
int main(int argc, char const *argv[])
{
int count = 0;
int a = 10, t= 0, b = 1;
for (size_t i = 0; i < 32; i++)
{
if (((a>>i)&1) == 1)
{
count++;
}
}
std::cout<<count;
return 0;
}
或
#include <iostream>
int main(int argc, char const *argv[])
{
int count = 0;
int a = 10, t = 0, b = 1;
while (a != 0)
{
a = (a - 1) & a;
count++;
}
std::cout<<count;
return 0;
}
----------------------------------------------
2
E:\Users\admin\Documents\VScode\Code>
==============================================
页:
[1]