基本的位运算符有6种:
https://www.cnblogs.com/qingsiburan/p/3824606.html
实例:
https://blog.csdn.net/u011402896/article/details/80727163
https://blog.csdn.net/yunyu5120/article/details/6692072
N皇后—位运算的应用
代码:
#include<stdio.h>
#include<string.h>
#define upperlim (1<<n)-1
int n,ans=0;
void test(int row,int ld,int rd){
int pos, p;
if ( row != upperlim ){
pos = upperlim & (~(row | ld | rd ));
while(pos){
p = pos & (~pos + 1);
pos = pos - p;
test(row | p, (ld | p) << 1, (rd | p) >> 1);
}
}
else
++ans;
}
int main(){
scanf("%d",&n);
test(0,0,0);
printf("%d\n",ans);
return 0;a
}
思路解析:
https://blog.csdn.net/kai_wei_zhang/article/details/8033194
经验总结:
1: p=pos & (~pos + 1);
表示取pos从右起的第一个数
2:如何关闭二进制中的任意一位?
实例:蓝桥杯第九届国赛第三题
只需令这一位异或1即可
代码:
#include<iostream>
#include<cstdio>
using namespace std;
int main(){
int pos=24,p;
p=pos&(~pos+1);
p<<=1;
pos=pos^p;
pos=pos^(pos&(~pos+1));
cout<<pos<<endl;
}