C++ 统计页码中每个数字出现的次数
#include <iostream>
#include <vector>
using namespace std;
int main() {
int N;
cin >> N;
vector<int> count(10, 0);
for (int i = 1; i <= N; i++) {
int num = i;
while (num > 0) {
int digit = num % 10;
count[digit]++;
num /= 10;
}
}
for (int i = 0; i < 10; i++) {
cout << count[i] << endl;
}
return 0;
}
该程序的思路是遍历每个页码,将每个页码的每一位数字拆分出来,然后统计每个数字出现的次数。首先我们定义一个长度为 10 的数组count,用来记录 0-9 每个数字出现的次数。然后使用一个循环遍历 1 到 N 的所有页码。对于每个页码,我们对其进行取余操作得到最后一位数字,然后将其在数组count中对应的位置加 1。接着将页码除以 10,以便处理下一位数字。最后,我们再遍历数组count,将每个数字出现的次数输出即可。
原文地址: https://www.cveoy.top/t/topic/qouB 著作权归作者所有。请勿转载和采集!