【UVA】1225 Digit Counting

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

题目:

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

分析:

求1至n的序列中有多少个0-9。两种求法,直接穷举和打表。直接穷举,则每输入一个n,就从1至n计算0-9的个数。打表则,将1-10000的情况先计算一遍; 可以先将 每个数的0-9的计数看作是,前一个数0-9的计数 + 数本身的情况。(这样就不需要每次都从1至n 一 一计算)

另外,看了别人的代码,发现也可先将1至n的序列输出整合为字符串(可以用sprintf()函数)。然后从0到strlen(num)循环计数,从而对每一位的对应0-9进行计数。

代码:

直接穷举(未打表):

#include <stdio.h>
#include <string.h>
int main()
{
	int T,n;
	int a[10];
	int i,num;
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n);
		memset(a,0,sizeof(a));
		for (i=1; i<=n; i++)
		{
			num = i;
			while (num)
			{
				a[num%10]++;
				num /= 10;
			}
		}
		for (i=0; i<10; i++)
		{
			if (i) printf(" ");
			printf("%d",a[i]);
		}
		printf("\n");
	}
	return 0;
}

打表法: 

#include <stdio.h>
#include <string.h>
int main()
{
	int T,n,i,j;
	int num,a[10000][10];
	memset(a,0,sizeof(a));
	for (i=1;i < 10000; i++)
	{
		num = i;
		for (j=0; i>1 && j<10; j++)
			a[i][j]=a[i-1][j];
		while (num)
		{
			a[i][num%10]++;
			num /= 10;
		}
	}
	scanf("%d",&T);
	while (T--)
	{
		scanf("%d",&n);
		for (i=0; i<10; i++)
		{
			if (i) printf(" ");
			printf("%d",a[n][i]);
		}
		printf("\n");
	}
	return 0;
}

 

全部评论

相关推荐

吴offer选手:学到了,下次面试也放张纸在电脑上,不然老是忘记要说哪几个点
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务