时间限制:CC++ 1000MS其他语言 2000MS内存限制:CC++ 256MB其他语言 512MB难度:中等出题人:描述给定一个十进制正整数n1≤n≤10000写下从1到n的所有整数然后数一下其中出现的数字1的个数。 例如当n=2时写下12。这样只出现了1个1;当n=12时写下123456789101112。这样出现了5个1。输入描述正整数n。1 ≤ n ≤ 10000。输出描述一个正整
#include <iostream>
#include <string>
using namespace std;
int countOne(int n) {
int count = 0;
for (int i = 1; i <= n; i++) {
string numStr = to_string(i);
for (char c : numStr) {
if (c == '1') {
count++;
}
}
}
return count;
}
int main() {
int n;
cin >> n;
int result = countOne(n);
cout << result << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/iCPr 著作权归作者所有。请勿转载和采集!