两个数a,b(1 <= a <= b <= 10^18)
输出共10行,分别是0-9出现的次数
10 19
1 11 1 1 1 1 1 1 1 1
计算[a,b]中0-9的次数。
1 #include <iostream> 2 #include <stdio.h> 3 #include <cstring> 4 #include <math.h> 5 #define ll long long 6 using namespace std; 7 8 ll dp[20]; 9 10 void init() { 11 memset(dp, 0, sizeof(dp)); 12 for(int i = 1; i <= 18; i ++) { 13 dp[i] = dp[i-1]*10 + pow(10,i-1); 14 } 15 } 16 ll count(ll r, int x) { 17 ll sum = 0, len = 0, cnt = 1, tail = 0, rr = r; 18 while(r) { 19 int tmp = r%10; 20 r /= 10; 21 len ++; 22 if(tmp > x) { 23 sum += dp[len-1]*tmp + cnt; 24 } else if(tmp == x) { 25 sum += dp[len-1]*tmp + tail + 1; 26 } else { 27 sum += dp[len-1]*tmp; 28 } 29 tail = tail + tmp*cnt; 30 cnt *= 10; 31 } 32 if(!x) { //是0的话就删除前缀为0的 33 ll ans = 1; 34 while(rr) { 35 sum -= ans; 36 ans *= 10; 37 rr /= 10; 38 } 39 } 40 return sum; 41 } 42 int main() { 43 init(); 44 ll a, b; 45 cin >> a >> b; 46 for(int i = 0; i < 10; i ++) { 47 cout << count(b,i) - count(a-1,i) << endl; 48 } 49 return 0; 50 }
原文:https://www.cnblogs.com/xingkongyihao/p/8893856.html