(解题报告)Uva-1225 --- Digit Counting

来源:互联网 发布:广州市失独数据 编辑:程序博客网 时间:2024/06/03 12:07

Digit Counting
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

题目大意:将前n个数顺次写在一起:123456789101112….数一数0~9一共出现多少次;
解题思路:
方法一:用笨办法,数据范围不大,将数据分为一位数,两位数,三位数,和四位数,分别求出他们的每位数,并将其对应数加1;
方法二:直接通过求每个数的最后一位,且求后将其减少一位,对应数加1;

具体代码如下:

方法一:

#include <stdio.h>#include <string.h>const int N=11;int main(){    int a[N],n,m,j,i,p,b,q,r,t;    scanf("%d",&n);    memset(a,0,sizeof(a));    while (n--)    {        scanf("%d",&m);        for(i=1;i<=m;i++)        {            if(i<10&&i>0)            {                a[i]++;            }            if(i<100&&i>9)            {                p=i%10;a[p]++;                q=i/10;a[q]++;              }            if(i<1000&&i>99)            {                r=i%10;a[r]++;                 p=i/10%10;a[p]++;                q=i/100;a[q]++;            }            if(i<10000&&i>999)            {                b=i/1000;a[b]++;                r=i/100%10;a[r]++;                q=i/10%10;a[q]++;                p=i%10;a[p]++;            }        }printf("%d",a[0]);             for(j=1;j<=9;j++)            printf(" %d",a[j]);            printf("\n");        for(j=0;j<=9;j++)        a[j]=0;    }     return 0;}

方法二:

#include <stdio.h>#include <string.h> int a[10]; void count( int n ){    do{        a[n % 10]++;        n /= 10;    }    while( n != 0 );}int main(){    int i,n,m,j;    scanf("%d", &n);    while(n--)    {        for( i = 0; i < 10; i++ )        a[i]=0;        scanf("%d",&m);        for( i=1; i<=m; i++)        count(i);        printf("%d",a[0]);         for(j=1;j<=9;j++)        printf(" %d",a[j]);        printf("\n");    }    return 0; }

仅代表个人观点,不喜勿喷,欢迎交流!
这里写图片描述

0 0
原创粉丝点击