编程之美--2.4 1的数目之扩展问题

思路与书中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;
}
    原文作者:David_DLUT
    原文地址: https://blog.csdn.net/David_DLUT/article/details/60348377
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞