数1的个数

GitHub跳转原题关系图返回列表

枚举 1 至 n,利用字符串 count 统计每个数中数字 1 的出现次数。

OJ: noi_openjudge

题目 ID: ch0105-40

难度:入门

标签:枚举字符串数位python

日期: 2026-07-30 23:01

题意

11nn 的所有整数写出,统计其中数字 1 总共出现多少次。

思路

数据范围只有 1000010000,逐个枚举即可。对每个数转换为字符串,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;
}

复杂度

nn 的十进制位数为 dd,时间复杂度为 O(nd)O(nd),额外空间复杂度为 O(d)O(d)

总结

范围较小时,枚举每个数并统计其字符串字符数,是可靠且易读的数位统计方法。