欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

写一个函数返回参数二进制中 1 的个数

程序员文章站 2024-03-15 15:49:30
...

一、看 i 能和 i-1 与多少次   

#include<stdio.h>
#include<stdlib.h>
int countbit(int i)
{
	int c = 0;
	while (i)
	{
		i &= (i - 1);
		
			c++;}
	    return c;


}
int main()
{
	int i = 254;
	int c=countbit(i);
	printf("%d\n", c);
	system("pause");
	    return 0;

}

二、

int count(int i)
{
	int c = 0;
	while(i)
	{
		if (i % 2 == 1)
		{
			c++;
		}
		i /= 2;
	}
	return c;
	
}
int main()
{
	
	int i = 10;
	int c = count(i);
	printf("%d\n", c);
	system("pause");
    return 0;
	
}

int count(int i)
{
	int c = 0;
	while (i)
	{
		if (i&1)
		{
			c++;
		}
		i>>=1;
	}
	return c;


}
int main()
{


	int i = 10;
	int c = count(i);
	printf("%d\n", c);
	system("pause");
	return 0;


}




相关标签: 返回1的个数