写一个函数返回参数二进制中 1 的个数 //比如: 15 0000 1111 4 个 1

写一个函数返回参数二进制中 1 的个数,比如: 15 0000 1111 4 个 1
三种方法
#include<stdio.h>

int count_bit(int n)
{
	int count = 0;
	//方法一
	//while (n)
	//{
	//	if (n % 2 == 1)//检测最低比特位是谁
	//	{
	//		count++;
	//	}
	//	n /= 2;//去掉最低比特位
	//}
	
	//方法二
	//int i = 0;
	//while (i<32)//如果是有符号数,右移过程中会导致他的符号位一直是1,形成死循环
	//{
	//	if (n & 1)//0000000001
	//	{
	//		count++;
	//	}
	//	n >>= 1;
	//	i++;
	//}
	//方法三
	while (n)
	{
		n &= (n - 1);//eg:5;0101&0100==0100 count++;0100&0011==0000 count++;n==0,结束循环,count==2;
		count++;
	}
	 
	return count;
}
int main()
{
	int n = 5;
	int i = count_bit(n);
	printf("%d\n", i);
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zn_wuxunian/article/details/79995074