统计数字问题
2017-08-30 19:17
267 查看
统计数字问题。给定一本书,其中包含n页,计算出书的全部页码中用到了多少个数字0…9。
样例输入:
11
样例输出:
1
4
1
1
1
1
1
1
1
1
解法1
解法2
解法3
样例输入:
11
样例输出:
1
4
1
1
1
1
1
1
1
1
解法1
#include<stdio.h> #include<math.h> #include<time.h> int main(){ int temp; int count; int n=12345; time_t begin,end; begin=time_t(); int a[10]={0}; for(int i=n;i>0;i--){ temp=i; while(temp){ a[temp%10]++; temp=temp/10; } } end=time_t(); for(int i=0;i<10;i++){ printf("%d\n",a[i]); } printf("运行时间%d\n",end-begin); return 0; }
解法2
#include<stdio.h> #include<math.h> #include<time.h> int main(){ int count; int n=12345; count=(int)log10(n); int low,high,temp; int a[10]={0}; time_t begin,end; begin=time_t(); for(int i=count;i>=0;i--){ high=n/(int)(int)pow(10,i)/10; temp=n/(int)(int)pow(10,i)%10; low=n%(int)(int)pow(10,i); printf("%d\t%d\t%d\t\n",high,temp,low); for(int j=0;j<temp;j++) a[j]+=(high+1)*(int)pow(10,i); a[temp]+=high*(int)pow(10,i)+low+1; for(int j=temp+1;j<=9;j++){ a[j]+=high*(int)pow(10,i); } } for(int k=count;k>=0;k--){ a[0]-=(int)pow(10,k); } end=time_t(); for(int i=0;i<=9;i++){ printf("%d\n",a[i]); } printf("运行时间%d\n",end-begin); return 0; }
解法3
#include<stdio.h> #include<math.h> int main(){ int i,j; int page=12345; int count=(int)log10(page); int temp; int a[10]={0}; for(i=count;i>=0;i--){ temp=page/(int)pow(10,i); page=page%(int)pow(10,i); a[temp]+=page+1; for(j=0;j<temp;j++){ a[j]+=(int)pow(10,i); } for(j=0;j<10;j++){ a[j]+=temp*i*(int)pow(10,i-1); } } for(j=0;j<=count;j++){ a[0]-=(int)pow(10,j); } for(i=0;i<10;i++){ printf("%d\n",a[i]); } return 0; }