C++ 统计 1 到 N 的整数中出现数字 '1' 的个数
以下是一个用 C++ 编写的程序,用于计算从 1 到 n 的所有整数中出现的数字 '1' 的个数:
#include <iostream>
#include <string>
int countOnes(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
std::string str = std::to_string(i);
for (char digit : str) {
if (digit == '1') {
count++;
}
}
}
return count;
}
int main() {
int n;
std::cout << "请输入一个正整数 n:";
std::cin >> n;
int onesCount = countOnes(n);
std::cout << "从 1 到 " << n << " 的所有整数中出现的数字 '1' 的个数为:" << onesCount << std::endl;
return 0;
}
在上述代码中,我们定义了一个 countOnes 函数,用于计算从 1 到 n 的所有整数中出现的数字 '1' 的个数。在 main 函数中,我们首先接收用户输入的正整数 n,然后调用 countOnes 函数计算出现的数字 '1' 的个数,并将结果输出。
请注意,这段代码基于题目要求,假设输入的 n 是一个十进制正整数。如果需要处理其他情况,例如负数、非十进制数等,请根据需要进行修改。
原文地址: https://www.cveoy.top/t/topic/b3yM 著作权归作者所有。请勿转载和采集!