x&(x-1)的妙用

一、求下面函数的返回值(微软)

int func(x) 
{ 
    int countx = 0; 
    while(x) 
    { 
          countx ++; 
          x = x&(x-1); 
     } 
    return countx; 
} 

功能:将x转化为2进制,看含有的1的个数。
注: 每执行一次x = x&(x-1),会将x用二进制表示时最右边的一个1变为0,因为x-1将会将该位(x用二进制表示时最右边的一个1)变为0。

运行结果

二、 判断一个数(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) == 优先级高于 &

运行结果

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81349232
x
x1