写一个函数返回参数二进制中 1 的个数
比如: 15 0000 1111 4 个 1
程序原型:
int count_one_bits(unsigned int value)
{
// 返回 1的位数
}
第一种方法:用模2除2的方法
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int count_one_bits(int m)
{
int count = 0;
while (m > 0)
{
if (m % 2)
{
count++;
}
m /= 2;
}
return count;
}
int main()
{
int m;
printf("请输入一位整数:\n");
scanf("%d", &m);
printf("%d\n", count_one_bits(m));
system("pause");
return 0;
}
第二种方法:右移的方法
*与1按位与,最低位为0,代表原数的最低位为0;最低位为1,代表原数的最低位为1。
*>>箭头向右,右移操作符。
#include<stdio.h>
#include<Windows.h>
#pragma warning(disable:4996)
int count_one_bits(int m)
{
int count = 0;
while (m > 0)
{
if (m & 1)
{
count++;
}
m = m >> 1;
}
return count;
}
int main()
{
int m;
printf("请输入一位整数:\n");
scanf("%d", &m);
printf("%d\n", count_one_bits(m));
system("pause");
return 0;
}
第三种方法:n&(n-1)的方法(最优解)
#include<stdio.h>
#include<stdio.h>
#pragma warning(disable:4996)
int count_one_bits(int m)
{
int count = 0;
while (m)
{
count++;
m = m&(m - 1);
}
return count;
}
int main()
{
int m;
printf("请输入一位整数:\n");
scanf("%d", &m);
printf("%d\n", count_one_bits(m));
system("pause");
return 0;
}