算法竞赛入门经典(第二版)第三章数组和字符串习题3-3数数字

把前n(n<=10000)个整数顺次卸载一起:123456789101112…数一数0~9各出现多少次(输出10个整数,分别是0,1,…,9出现的次数)

#include<stdio.h>
#define N 100000
char s[N],temp[10];
int count[10];
int main()
{
    int t,n,i;
    scanf("%d",&t);//判断你要输入的次数
    while(t--)
    {
        memset(count,0,sizeof(count));//清空数组count
        memset(s,0,sizeof(s));//清空数组s
        scanf("%d",&n);
        for(i=1;i<=n;i++){
            sprintf(temp,"%d",i);//将i输入到temp数组中
            strcat(s,temp);//连接s和temp
        }
        for(i=0;i<strlen(s);i++)
            count[s[i]-'0']++;//相应位置的数字累加上去
        for(i=0;i<10;i++){
            printf("%d",count[i]);
            if(i!=9) printf(" ");
            else printf("\n");
        }
    }
    return 0;
 }

猜你喜欢

转载自blog.csdn.net/qq_43233736/article/details/83099425