从简单到复杂的分析,从1位数开始,找到规律,抽象出公式。 体现的是分解问题的能力,找到问题切入点的能力。 个人觉得书中的公式有一点问题,对于命题2的公式应该为f( 10^n - 1) = n * (10^ (n-1) ) 代码: //编程之美--求1的个数 //如果要求f(N) = N的最大解N,先证明 //f( 10^n - 1) = n * (10^ (n-1) ) #include <iostream> using namespace std; int NewPro(int n) { unsigned iFactor = 1; unsigned iTotal = 0; unsigned iLower = 0; unsigned iHighter = 0; unsigned iCurrent = 0; while (n/iFactor) { //iLower = n%iFactor; iLower = n %iFactor; iCurrent = (n/iFactor)%10; iHighter = n/(iFactor*10); iTotal += iHighter * iFactor; switch(iCurrent) { case 0://通过分析可知,当当前位为0时,1的个数只受高位的影响 break; case 1://为1时,受高位和低位的影响 iTotal += iLower + 1; break; default://大于1的时候为高位的数+1 iTotal += iFactor; } iFactor*=10; } return iTotal; } int main() { int m; while (cin>>m) { cout<<Process(m)<<endl; cout<<NewPro(m)<<endl; } return 0; }