2021_11_18
第一种方法:采取的是取余、再除法
(此做法就类似于对于一个十进制的数,如何得到它的每一位)
#include <stdio.h>
int count_number_if_1(unsigned int n)
{
int c = 0;
while (n)
{
if (1 == (n % 2))
{
c++;
}
n /= 2;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = count_number_of_1(n);
printf("%d\n", ret);
return 0;
}
第二种方法: 利用 & 按位与操作符(两数同为都为1才为1)
#include <stdio.h>
int count_number_of_1(int n)
{
int c = 0;
while (n)
{
if (1 == (n & 1))
{
c++;
}
n >>= 1;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = count_number_of_1(n);
printf("%d\n", ret);
return 0;
}
第三种方法:
#include <stdio.h>
int count_number_of_1(int m)
{
int c = 0;
while (m)
{
m = m & (m - 1);
c++;
}
return c;
}
int main()
{
int n = 0;
scanf("%d", &n);
int ret = count_number_of_1(n);
printf("%d\n", ret);
return 0;
}