位与运算符 "&" 运算符 x=x&(x-1)

    技术2022-05-20  37

    规律总结:

    每执行一次x = x&(x-1),效果 使得 x二进制的最后一个 “1”变为零。

    如 x=8(10)

    8&7

    01000(2)& 00111(2)

    结果为0

    如 x=3(10)

    011 (2)& 010(2)

    结果为10(2)

     

    用法:

    统计1的个数

    求下面函数的返回值

    ---------------------------------------int func(int x){    int countx = 0;    while(x)    {        countx++;        x = x&(x-1);    }    return countx;} ---------------------------------------假定x = 999910011100001111答案: 8思路: 将x转化为2进制,看含有的1的个数。判断一个数(x)是否是2的n次方-------------------------------------#include <stdio.h>int func(int x){    if( (x&(x-1)) == 0 )        return 1;    else        return 0;}int main(){    int x = 8;    printf("%d/n", func(x));}-------------------------------------注: (1) 如果一个数是2的n次方,那么这个数用二进制表示时其最高位为1,其余位为0。(2) == 优先级高于 &

     

     

     

    #include <stdio.h>

     

    /*输出十进制整数的二进制表达式,32位*/void outBin(int n){       int a[32], i = 0;        if (n == 0)    {        printf("0");        return;    }

        while (n > 0)    {        a[i++] = n % 2;        n >>= 1;    }

        while (i--)    {        printf("%d", a[i]);    }}

    /*统计一个整数二进制表达式中1的个数*/int func(int x){    int countx = 0;    while (x)    {        countx++;        x = x & (x-1);    }

        return countx;}

    void funy(int y){    int county = 0;

        printf("请看这个整数%d/n",y);    if (((y & (y - 1)) == 0) && (y > 0))    /*注意:【==】 优先级高于 【&】*/    {        while((y%2) == 0)        {            y >>= 1;            county++;        }        printf("它是2的%d次方/n",county);    }    else    {        printf("这个整数不是2的次方数!");    }}

    int main(){    int x = 999;    int y = 1024;

        printf("请看这个整数%d/n",x);    printf("二进制表达为");    outBin(x);    printf("/n");    printf("共有%d个1/n",func(x));

        printf("通过(x &= x-1)变换展示如下:/n");    while (x)    {        outBin(x);        printf("/n");        x &= x-1;    }    printf("/n");

        funy(y);

        getchar();    return 0;}

    转自百度空间http://hi.baidu.com/hh20040410/blog/item/c9512cd67ef62a2706088b09.html

     


    最新回复(0)