首页 > 技术文章 > vijos-记数问题

gcter 2018-01-10 17:01 原文

描述

试计算在区间 1 到 n 的所有整数中,数字 x(0 ≤ x ≤ 9)共出现了多少次?例如,在 1 到 11 中,即在 1、2、3、4、5、6、7、8、9、10、11 中,数字 1 出现了 4 次。

格式

输入格式

输入共 1 行,包含 2 个整数 n、x,之间用一个空格隔开。

输出格式

输出共 1 行,包含一个整数,表示 x 出现的次数。

样例1

样例输入1

11 1

样例输出1

4

限制

每个测试点1s。

提示

对于 100%的数据,1≤ n ≤ 1,000,000,0 ≤ x ≤ 9。

来源

NOIP 2013 普及组

/*题目主要是一个取模的过程,也可以用数组实现/*/
//一般实现
#include<iostream>
using namespace std;
int main()
{
    long long int count_num,end_num,total=0;
    int i, j;
    cin>>end_num>>count_num;
    for (i = 1; i <= end_num; i++)
    {
        j = i;
        while (j != 0)
        {
            if (count_num == j % 10)
            {
                total++;
            }
            j /= 10;
        }
    }
    cout<<total;

    return 0;
}
//数组实现  逐个累加
#include<iostream>
using namespace std;
int  total[10];
void  count_amount(int  n)
{
    while (n != 0)
    {
        total[n % 10]++;
        n /= 10;
    }
    return;
}
int main()
{
    int count_num, end_num;
    int i;
    cin >> end_num >> count_num;
    for (i = 1; i <= end_num; i++)
    {
        count_amount(i);
    }
    cout << total[count_num]<<endl;

    return 0;
}

 

推荐阅读