思路与书中2.4的类似,只是把十进制换成了二进制,只需在iFactor*10的地方,改成iFactor*2即可。
代码如下:
#include <iostream>
#include<bitset>
using namespace std;
const unsigned SYSTEM = 2;
unsigned long Sum1s(unsigned long n)
{
unsigned long iCount = 0;
unsigned long iFactor = 1;
unsigned long iLowerNum = 0;
unsigned long iCurrNum = 0;
unsigned long iHigherNum = 0;
while (n / iFactor != 0)
{
iLowerNum = n - (n / iFactor) * iFactor;
iCurrNum = (n / iFactor) % SYSTEM;
iHigherNum = n / (iFactor * SYSTEM);
switch (iCurrNum)
{
case 0:
iCount += iHigherNum * iFactor;
break;
case 1:
iCount += iHigherNum * iFactor + iLowerNum + 1;
break;
default:
iCount += (iHigherNum + 1) * iFactor;
break;
}
iFactor *= SYSTEM;
}
return iCount;
}
int main()
{
unsigned long n = 0x4;
cout << "binary number: " << bitset<8>(n) << endl;
cout << "number of 1: " << Sum1s(n) << endl;
system("pause");
return 0;
}