编程之美-----1的个数

#include <stdio.h>
#include <stdlib.h>
int SUMone(int N)
{
    int iter = 0, icount = 0 , Ntemp, bitNum = 0;
    Ntemp = N;
    for(iter = 1; iter <= N; iter++)
    {
        Ntemp = iter;
        while(Ntemp != 0)
        {
            bitNum = Ntemp % 10;
            if(bitNum == 1)
            {
               icount++;
            }
            Ntemp = Ntemp / 10;
        }
    }
    return icount;
}


    //核心算法,高效的核心算法来计算f(N)

    int Sumbetter(int N)
    {
        int icount = 0;
        int highNum = 0;
        int currNum = 0;
        int lowNum = 0;
        int ifactor = 1;
        while(N / ifactor != 0)
        {
            highNum = N / (ifactor * 10);
            currNum = (N / ifactor) % 10;
            lowNum = N - (N / ifactor) * ifactor;
            switch(currNum)
            {
                case 0: 
                    icount = icount + highNum * ifactor;
                    break;
                case 1: 
                    icount = icount + highNum * ifactor + lowNum + 1;
                    break;
                default: 
                    icount = icount + (highNum + 1) * ifactor;
                    break;
            }
            ifactor = ifactor * 10;
        }
        return icount;
    }

int main()
{
    int testNum;
    testNum = 205;
    printf("the amount of the Number is %d\n",SUMone(testNum));
    printf("the amount of the Number is %d",Sumbetter(testNum));
    return 0;
}
    原文作者:ymjystu
    原文地址: https://blog.csdn.net/qq_24338883/article/details/60873698
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞