美文网首页
UVa1225 数数字 习题3-3

UVa1225 数数字 习题3-3

作者: hhallelujah | 来源:发表于2017-01-25 21:44 被阅读0次

3-3 「UVa1225」数数字:

把前n(n<=1000)个整数顺次写在一起:89101112...数一数09各出现多少次(输出10个整数,分别是09出现的次数)

代码

#include<stdio.h>
#include<string.h>
#define maxn 100000 //由于N<=1000所以数组要开大,要存10000个数字。 否则re
void makes(int n,char *s)
{
    char temp[10];
    for(int i=1;i<=n;i++){
        sprintf(temp,"%d",i);   //int型赋值给char型数组用sprintf函数 
        strcat(s,temp);
    }
    //printf("%s\n",s);
}

int main()
{
    int t,n,count[10];
    char s[maxn];
    scanf("%d",&t);
    while(t--){
        int tot=0;
        memset(count,0,sizeof(count));
        memset(s,0,sizeof(s));
        scanf("%d",&n);
        makes(n,s);
        for(int d=0;d<=9;d++){
            for(int i=0;i<strlen(s);i++){
                if(s[i]-'0'==d) count[d]=++tot;
            }
        printf("%d",count[d]);
        if(d!=9) printf(" ");
        else printf("\n");
        tot=0; 
        }
    }
    return 0;
}  

简化版:

#include<stdio.h>
#include<string.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));
        memset(s,0,sizeof(s));
        scanf("%d",&n);
        for(i=1;i<=n;i++){
            sprintf(temp,"%d",i);
            strcat(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;
 } 
  • 注意
  • 输出格式每个答案之间要空一行

相关文章

网友评论

      本文标题:UVa1225 数数字 习题3-3

      本文链接:https://www.haomeiwen.com/subject/vecxittx.html