位运算

来源:互联网 发布:帝国cms广告代码 编辑:程序博客网 时间:2024/05/17 08:43

位运算


位运算知识详解:Matrix67博客文章http://www.matrix67.com/blog/archives/122



两个数交换:

void swap(int a, int b){a = a ^ b;b = a ^ b;a = a ^ b;}


计算二进制中1的个数:

#include<stdio.h>int slove(int x){x = (x & 0x55555555) + ((x >> 1) & 0x55555555);x = (x & 0x33333333) + ((x >> 2) & 0x33333333);x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);x = (x & 0x0000FFFF) + ((x >> 16) & 0x0000FFFF);return x;}int main (){int x;while(scanf("%d", &x)!=EOF){x = slove(x);printf("%d\n", x);}return 0;}


n皇后问题

#include<stdio.h>int upperlim ,sum, n;void test(long row,long ld,long rd){    long pos,p;    if( row!=upperlim)    {        pos=upperlim&~(row | ld | rd);        while (pos!=0)        {            p=pos&-pos;            pos=pos-p;            test(row+p,(ld+p)<<1,(rd+p)>>1);        }    }    else sum++;}int main (){while(scanf("%d", &n),n){upperlim = (1 << n) - 1;sum = 0;test(0,0,0);printf("%d\n", sum);}return 0;}


原创粉丝点击