给定两个整数 a 和 b,求 a 和 b 之间的所有数字中 0∼9 的出现次数。
例如,a=1024,b=1032a=1024,b=1032,则 a 和 b 之间共有 9 个数如下:
1024 1025 1026 1027 1028 1029 1030 1031 1032
其中
0
出现 10 次,1
出现 10 次,2
出现 7 次,3
出现 3 次等等…
我们可以构造这样一个函数count(n,x)
求出来1~n中x出现的次数,通过类似前缀和的公式来得到另一个区间的个数
那么怎么求出来呢,分情况讨论。
我们求出来x在每一位在这个区间内每一位出现的次数累加起来就是答案。
比如求当x = 1的个数,在1~abcdefg上的个数
求 1 在第4位上出现的次数。
1 <= xxx1yyy <= abcdefg
第一种情况:当xxx = 000~abc-1的时候,显然此时后面的 yyy 可以随便取数,显然是000~999,这时候方案数是 abc * 1000个
第二种情况:当xxx = abc的时候:
1. d < 1,abc1yyy > abc0efg,显然第4位不是1,方案数显然为0
2. d = 1,abc1yyy,yyy = 000 ~ efg,那么方案数就是efg + 1
3. d > 1,显然第四位也只会出现一次1,但是这次的 1 相较于上面d = 1的情况下是拉满的,也就是方案数是 1000,即 999 + 1
这个题还存在两个边界情况
首先当我们要求的 x 出现在第一位的时候,显然第一种情况是不存在的,因为我们在这个数的前面是没有数的。
其次如果是问 0 出现的次数的话,在第一种分类情况下,我们就不能从000开始了,因为前导0是没有意义的,所以就应该从001开始到最后,所以方案数应该是 (abc - 1) * 1000
// Problem: 计数问题
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/description/340/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// Code by: ING__
//
// Powered by CP Editor (https://cpeditor.org)
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int power10(int n){
int ans = 1;
while(n--){
ans *= 10;
}
return ans;
}
int wei(int n){
int ans = 0;
while(n){
n /= 10;
ans++;
}
return ans;
}
int count(int n, int x){
if(!n) return 0;
int w = wei(n);
int ans = 0;
for(int i = 1; i <= w; i++){
int j = power10(w - i); // 这里为什么是w - i而不是 i 呢;因为我们这里的第 i 位是十进制下的从左往右的位,也就是从大到小的位数来看的
int r = n % j;
int l = n / j / 10;
int d = n / j % 10;
// cout << l << ' ' << r << " " << d << endl;
if(x) ans += l * j;
else ans += (l - 1) * j;
if(d == x) ans += r + 1;
if(d > x) ans += j;
}
return ans;
}
int main(){
int a, b;
while(cin >> a >> b, a || b){
if (a > b) swap(a, b);
for(int i = 0; i <= 9; i++){
cout << count(b, i) - count(a - 1, i) << " ";
}
cout << endl;
}
return 0;
}
感谢大佬讲解qwq 链接