C++ 算法:统计书籍页码数字出现次数
以下是使用 C++ 编写的算法实现:
#include <iostream>
#include <vector>
std::vector<int> countDigits(int n) {
std::vector<int> count(10, 0); // 用于计数的数组,初始化为0
for (int i = 1; i <= n; i++) {
int num = i;
while (num > 0) {
int digit = num % 10; // 获取当前数字的个位数
count[digit]++; // 对应数字的计数加1
num /= 10; // 去掉个位数
}
}
return count;
}
int main() {
int n;
std::cout << "请输入书的总页码n:";
std::cin >> n;
std::vector<int> digitCount = countDigits(n);
std::cout << "数字0-9在页码中出现的次数分别为:" << std::endl;
for (int i = 0; i < 10; i++) {
std::cout << i << ": " << digitCount[i] << std::endl;
}
return 0;
}
该算法首先定义了一个长度为10的数组 count,用于记录数字 0-9 在页码中出现的次数。然后使用循环从 1 到 n 遍历每个页码,对每个页码进行数字拆解,将数字的个位数作为索引,将对应的计数加 1。最后,打印出数字 0-9 在页码中出现的次数。
使用该算法,可以得到书的全部页码中数字 0-9 分别出现的次数。
原文地址: https://www.cveoy.top/t/topic/hwLX 著作权归作者所有。请勿转载和采集!