获取1的总数源代码

// CountOnes.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> using namespace std; int GetOneCount(int nNum); int GetOneCountEx(int nNum); int main() { int i = 0; /*for (i = 0; i < 0xffff; i++) { cout << "i = " << i << " 1s = " << GetOneCount(i) << endl; }*/ cout << "i = " << 0xffff - 1<< " 1s = " << GetOneCountEx(0xffff - 1) << endl; return 0; } int GetOneCount(int nNum) { int i = 0; int nCount = 0; int nTemp = 0; for (i = 0; i < nNum; i++) { nTemp = i; while (nTemp) { if (1 == nTemp % 10) { nCount++; } nTemp /= 10; } } return nCount; } int GetOneCountEx(int nNum) { int nCount = 0; int nFac = 1; int nLowNum = 0; int nHiNum = 0; int nCurrNum = 0; while (nNum / nFac) { nLowNum = nNum - (nNum / nFac) * nFac; nHiNum = nNum / (nFac * 10); nCurrNum = (nNum / nFac) % 10; int nTemp = nCount; switch (nCurrNum) { case 0: nCount += nHiNum * nFac; break; case 1: nCount += nHiNum * nFac + nLowNum + 1; break; default: nCount += (nHiNum + 1) * nFac; break; } cout << "nCount = " << nCount << "/tnCurrCount = " << nCount - nTemp << "/tnLowNum = " << nLowNum << "/tnHiNum = " << nHiNum << "/tnCurrNum = " << nCurrNum << endl; nFac *= 10; } return nCount; }  

你可能感兴趣的:(获取1的总数源代码)