Digit Counting UVA – 1225

Trung is bored with his mathematics homeworks. He takes a piece of chalk and starts writing a sequence of consecutive integers starting with 1 to N (1 < N < 10000). After that, he counts the number of times each digit (0 to 9) appears in the sequence.

For example, with N = 13, the sequence is: 12345678910111213

In this sequence, 0 appears once, 1 appears 6 times, 2 appears 2 times, 3 appears 3 times, and each digit from 4 to 9 appears once. After playing for a while, Trung gets bored again. He now wants to write a program to do this for him. Your task is to help him with writing this program. Input The input file consists of several data sets. The first line of the input file contains the number of data sets which is a positive integer and is not bigger than 20. The following lines describe the data sets. For each test case, there is one single line containing the number N. Output For each test case, write sequentially in one line the number of digit 0, 1, . . . 9 separated by a space.

Sample Input

2 3 13

Sample Output

0 1 1 1 0 0 0 0 0 0 1 6 2 2 1 1 1 1 1 1

问题链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3666

问题:输入一个n将1到n,n个数字每个连在一起,统计1~9每种数字出现的次数

解题思路:

1.紫书上的思路是打表:由于n的值比较小。令c[n][k]表示前n个数字写在一起,k(k= 0~9)总共出现几次,则有c[n+1][k] = c[n][k]+x,其中x是在n+1中出现的次数。提前计算最后需要的时候直接输出结果即可

2.我的思路,没输入一个n计算一次,通过while与%取出每一位数字,再计算次数

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int N=10;
int a[N]={0};

int  main(){
int t;
cin>>t;
while(t--){
    int n;
    int now;
    cin>>n;
    memset(a,0,sizeof(a));

    for(int i=1; i<=n; i++){
        now=i;
        while(now){
            a[now%10]++;
            now/=10;
        }
    }

for(int i=0; i<N; i++){
    i==0?cout<<a[i]:cout<<" "<<a[i];
}
cout<<endl;
}

return 0;
}
发布了66 篇原创文章 · 获赞 3 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览