POJ NOI0105-40 数1的个数

问题链接POJ NOI0105-40 数1的个数



总时间限制:
1000ms
内存限制:
65536kB
描述

给定一个十进制正整数n,写下从1到n的所有整数,然后数一下其中出现的数字“1”的个数。

例如当n=2时,写下1,2。这样只出现了1个“1”;当n=12时,写下1,2,3,4,5,6,7,8,9,10,11,12。这样出现了5个“1”。
输入
正整数n。1 <= n <= 10000。
输出
一个正整数,即“1”的个数。
样例输入
12
样例输出
5
提示

来源
习题(8-11) 医学部 2010 期末试题 尤朝


问题分析

  这是一个进制有关的计算问题。

  取出各位数字是一种套路。

程序说明

  把功能封装到函数中,是一种好的做法

  使用常量可以增强程序的可重用性。





参考链接:(略)。




AC的C++语言程序:

#include <iostream>

using namespace std;

const int BASE10 = 10;
const int DIGIT = 1;

int countDigit(int n, int digit)
{
    int count;

    count = 0;
    while(n) {
        if(n % BASE10 == digit)
            count++;
        n /= BASE10;
    }

    return count;
}

int main()
{
    int n, count;

    cin >> n;

    count = 0;
    for(int i=1; i<=n; i++)
        count += countDigit(i, DIGIT);

    cout << count << endl;

    return 0;
}



原文地址:https://www.cnblogs.com/tigerisland/p/7563812.html