题目描述
输入一个int型的正整数,计算出该int型数据在内存中存储时1的个数。
输入描述:
输入一个整数(int类型)
输出描述:
这个数转换成2进制后,输出1的个数
示例1
输入
5
输出
2
本题考查知识点:二进制、位运算
本题难度:初级
需要注意的点:需要将iValue转换为无符号整形
/*
功能:
输入:整型
输出:
返回:返回1的个数
*/
int GetCount(int iValue)
{
int count=0;
unsigned int outValue = (unsigned int)iValue;//如果不转换成无符号整形,负数 outValue/2 后存储的将是补码,导致统计错误
while(outValue)
{
if(outValue%2)//余2相当于判断是否为1
{
count++;
}
outValue = outValue/2;//除以2等于右移一位
}
return count;
}
get的知识点:
1.以5(0101)为例,当运行1次后,outValue为2,进入if语句后,2%2==0,此时程序还没有结束,在outValue = outValue/2;后outValue为1,还可以运行1次,此时count&