枚举 1 至 n,利用字符串 count 统计每个数中数字 1 的出现次数。
OJ: noi_openjudge
题目 ID: ch0105-40
难度:入门
标签:枚举字符串数位python
日期: 2026-07-30 23:01
题意
把 1 总共出现多少次。
思路
数据范围只有 count("1") 给出它内部数字 1 的出现次数,再用生成器表达式求和。
代码
Python代码
python
limit = int(input())
answer = sum(str(number).count("1") for number in range(1, limit + 1))
print(answer)C++代码
cpp
#include <cstdio>
int main(){
int i,n;
int cnt=0;
scanf("%d",&n);
for (i=1;i<=n;i++){
int t= i;
while( t != 0){
int a = t % 10;
if( a == 1){
cnt++;
}
t /= 10;
}
}
printf("%d\n",cnt);
return 0;
}复杂度
设
总结
范围较小时,枚举每个数并统计其字符串字符数,是可靠且易读的数位统计方法。