给出一段区间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出现的次数/** *从copy 代码到理解代码, */ #include<iostream> #include<stdio.h> #include<cmath> #include<algorithm> using namespace std; typedef long long LL; const int MAXN = 20; LL dp[MAXN] = {0}; void init(){//初始化用到的数据DP,便于计算1-n中k出现的个数 for(int i=0;i<=MAXN;i++){ dp[i] = i * (LL) pow(10,i-1); } } LL solve(LL n,int k){//计算1-n之间,k出现的次数 int len = 0; LL digit = 0,tail = 0,radix = 1,ans = 0,cnt = n;//cnt用于去掉多余的0 while(n){ digit = n % 10; n /= 10; len ++; if(digit > k) ans += radix+digit*dp[len-1]; else if(digit == k) ans += tail+1+digit*dp[len-1]; else ans += digit*dp[len-1]; tail += radix*digit; radix *= 10; } if(k == 0){//去掉多余的0 LL m = 1; while(cnt){ ans -= m; m *= 10; cnt /= 10; } } return ans; } int main() { LL a,b; init(); while(cin>>a>>b){ for(int i=0;i<10;i++){ cout<<solve(b,i)-solve(a-1,i)<<endl; } } return 0; }
参考(copy):
http://blog.csdn.net/zwj1452267376/article/details/52894813
http://blog.csdn.net/u010885899/article/details/50763108