我们都知道,数字在计算机中是以二进制序列存储的,那么要想得到其二进制序列中一的个数有哪些方法呢?下面我就来介绍几种方法。
第一种方法如下:
#include<stdio.h>
#include<Windows.h>
int main()
{
int input = 0;
int count = 0;
printf("请输入一个数:");
scanf("%d", &input);
while(input)
{
if(input%2 == 1)
{
count++;
}
input /= 2;
}
printf("count = %d\n", count);
system("pause");
return 0;
}
这种方法是最容易想到,但是这种方法也存在问题。假如输入的数是一个负数,那么结果如何呢?
这样这个代码就存在问题。我们都知道-1的二进制序列是32个1,但是在该程序中,显示结果却是0,那么如何解决呢,接下来就引出第二种方法:
#include<stdio.h>
#include<Windows.h>
int main()
{
int input = 0;
int count = 0;
int i = 0;
printf("请输入一个数:");
scanf("%d", &input);
for(i=0; i<32; i++)
{
if(((input>>i)&1) == 1)
{
count++;
}
}
printf("count = %d\n", count);
system("pause");
return 0;
}
在该方法中,这个问题就得到了很好的解决。对于一个数的二进制序列,对其每一位进行右移操作,同时和1进行相与,并判断运算结果,由此得到二进制序列中1的个数。对于-1的检验结果如下:
此外,还有第三种方法,也是可以用来计算二进制序列中1的个数,具体代码如下:
#include<stdio.h>
#include<Windows.h>
int main()
{
int input = 0;
int count = 0;
printf("请输入一个数:");
scanf("%d", &input);
while(input>0)
{
input = input&(input-1);
count++;
}
printf("count = %d\n", count);
system("pause");
return 0;
}
在这里,以数字15来进行举例。我们都知道15的二进制序列为1111,而14的二进制序列则为1110,将两个数进行相与,则得到第二次的input为1110,,以此类推,13的二进制序列为1101,与14相与得到第三次的input为1100,当1100再次减一的时候,得到1011,再次相与得到第四次的input为1000。当1000和0111相与,此时input为0,不再进入while,得到count为4。