基准时间限制:1 秒 空间限制:131072 KB 分值: 10
难度:2级算法题
给出一段区间a-b,统计这个区间内0-9出现的次数。
比如 10-19,1出现11次(10,11,12,13,14,15,16,17,18,19,其中11包括2个1),其余数字各出现1次。
Input
两个数a,b(1 <= a <= b <= 10^18)
Output
输出共10行,分别是0-9出现的次数
Input示例
10 19
Output示例
1 11 1 1 1 1 1 1 11
如果是第一次接触这样的题目,推荐先看这个1009 数字1的数量 再次解释一下,随便举个数 456 求2出现的次数 我们在这里值分析百位的4 因为 4>2 把百位看成2,十位和个位有100种方案 然后百位可以取 0 1 2 3 这4个数,每个数对应有dp[2]
#include<cstdio> #include<cstring> #include<cmath> #define LL long long LL dp[20]; void Init() { memset(dp,0,sizeof(dp)); int i; for(i=1;i<20;++i) dp[i]=dp[i-1]*10+pow(10,i-1); } LL solver(LL n,LL to) { LL temp=1,tn=n,rail=0,result=0,digit=0; LL len=0; while(tn) { digit=tn%10; tn/=10; ++len; if(to==digit) { result+=rail+1+digit*dp[len-1]; } else if(digit>to) { result+=digit*dp[len-1]+temp; } else if(digit<to) result+=digit*dp[len-1]; rail+=digit*temp; temp*=10; } if(to==0) { temp=1; while(n) { result-=temp; n/=10; temp*=10; } } return result; } int main() { Init(); LL a,b; while(scanf("%lld%lld",&a,&b)!=EOF) { LL i; for(i=0;i<=9;++i) printf("%lld\n",solver(b,i)-solver(a-1,i)); } }