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

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

程序员文章站 2022-07-15 10:02:00
...
#define _crt_secure_no_warnings 1
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int count_one_bits(unsigned int value) //不需要判断%2
{
	int count = 0;
	while (value != 0)
	{
		value = value & (value - 1);
		count++;
	}
	return count;
}

int count_one_bits(unsigned int value)  //一定要判断%2
{
	int count = 0;
	while (value != 0)
	{
		if (value % 2 == 1)
		{
			count++;
		}
		//value = value >> 1;
		value = value / 2;
	}
	return count;
}

int main()
{
	int value = 0;
	printf("input the number :");
	scanf("%d", &value);
	printf("one binary is : %d\n", count_one_bits(value));
	system("pause");
	return 0;
}