位操作:一个整数的二进制表示中 有多少个1?

#include <stdio.h>

int countHowMuchOne( int number )
{
	int count = 0;
	while ( number )
	{
		number = number & ( number-1 );
		++count;
	}

	return count;
}

int main()
{
	int num  = 11;
	int count = 0;
	count = countHowMuchOne( num);
	printf("%d'binary format has %d bit 1 \n", num, count);

	return 0;
}

// 解答

若一个数最右边一位为1,例如 x = 011011,x-1 = 011010,两者做&操作,会将最右边一位1消掉

若一个数最右边一位为0, 例如 x = 101100,x-1 = 101011,两者做&操作,同样会将最右边的一位1消掉

因为减一操作使得,原来的数x 的最低位从右向左直到遇到一个1,这些bit位都会取反,做&操作会将最右边的一位1消掉

 

#include <stdio.h>

int countHowMuchOne2( int number )
{
	int count = 0;
	int lastBit = 0;
	while ( number )
	{
		lastBit = number & 1;
		if ( lastBit )
		{
			++count;
		}
		number = number >> 1;
		
	}

	return count;
}

int main()
{
	int num  = 11;
	int count = 0;
	count = countHowMuchOne2( num);
	printf("%d'binary format has %d bit 1 \n", num, count);

	return 0;
}
// 解答 思路二:每次取最后一位和1与运算,若结果为1,说明末尾为1,否则末尾为0


// 扩展问题,如何判断一个数是否是2的n次方? 即: x ?= 1 << 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));
}

// 解答

一个数是2的n次方,则其二进制表示中最高位为1,其余位为0,而且只有一个1,那么 x&(x-1)必为0


// 其他关于位操作的例子

如何快速得到一个数的7倍? 答案: x << 3  - x

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值