51nod自学日记-位运算

引入

今天,我有时间,在51nod上学习了位运算。

一、位运算的计算

位运算符号 名称 效果
& 按位与 如果两个相应的二进制位都为 \(1\),则该位的结果值为 \(1\),否则为 \(0\)
| 按位或 两个相应的二进制位中只要有一个为 \(1\),该位的结果值为 \(1\) ,否则为 \(0\)
^ 按位异或 若参加运算的两个二进制位值相同则为 \(0\),否则为 \(1\)
~ 取反 ~是一元运算符,用来对一个二进制数按位取反,即将 \(0\)\(1\),将 \(1\)\(0\)
<< \(N\) 左移 用来将一个数的各二进制位全部左移 \(N\) 位,右补 \(0\)
>> \(N\) 右移 将一个数的各二进制位右移 \(N\) 位,移到右端的低位被舍弃,对于无符号数,高位补 \(0\)

二、位运算的灵活巧用

  • 以前我们判断一个数 \(n\) 是奇数还是偶数通常使用 \(n\%2\) 的结果来判断, \(1\) 为奇数 \(0\) 为偶数, 现在我们也可以使用 & 操作来判断奇偶,\(n\&1\) 的结果就是取 \(n\) 的二进制的最末位。二进制的最末位为 \(0\) 表示 \(n\) 为偶数,最末位为 \(1\) 表示 \(n\) 为奇数。

  • 反转二进制,只需要将想要反转的位异或 \(1\) 就可以, 如:\(1010\) $ xor $ \(1111\) \(=\) \(0101\)

三、51NOD同步学-位运算

2106 一个奇数次

#include <bits/stdc++.h>
//#undef _agree_
//#define _agree_
//#undef JTBG_ALL
//#define JTBG_ALL
//#ifdef _agree_
//#include "jtbg.h"
//#else
//#error "can not agree"
//#endif
using namespace std;
int main()
{
	int n;
	cin>>n;
	int ans=0;
	for(int i=0;i<n;i++)
	{
		int x;
		cin>>x;
		ans^=x;
	}
	cout<<ans;
	return 0;
}

3216 授勋

#include <bits/stdc++.h>
//#undef _agree_
//#define _agree_
//#undef JTBG_ALL
//#define JTBG_ALL
//#ifdef _agree_
//#include "jtbg.h"
//#else
//#error "can not agree"
//#endif
using namespace std;
int main()
{
	int n;
	cin>>n;
	for(int i=0;i<n;i++)
	{
		int x,ans=0;
		cin>>x;
		while(x!=0)
		{
			if(x&1) ans++;
			x=x>>1;
		}
		cout<<ans<<endl;
	}
}

2102 或减与

#include <bits/stdc++.h>
//#undef _agree_
//#define _agree_
//#undef JTBG_ALL
//#define JTBG_ALL
//#ifdef _agree_
//#include "jtbg.h"
//#else
//#error "can not agree"
//#endif
using namespace std;
int main()
{
	int a,b;
	cin>>a>>b;
	cout<<(a^b);
	//我们发现两个数相减后得到的结果同 xor 运算完全一致,因此直接输出 a xor b 即可。
}

2653 区间xor

#include <bits/stdc++.h>
//#undef _agree_
//#define _agree_
//#undef JTBG_ALL
//#define JTBG_ALL
//#ifdef _agree_
//#include "jtbg.h"
//#else
//#error "can not agree"
//#endif
using namespace std;
int F(int n)
{
	if(n&1)
	{
		return ~(n%4)/2;
	}
	else
	{
		return F(n-1) ^ n;
	}
}
int main()
{
	int a,b;
	cin>>a>>b;
	cout<<(F(b)^F(a-1));
}
posted @ 2026-01-08 20:26  jtbg  阅读(0)  评论(0)    收藏  举报