1049 Counting Ones

本文详细解析了1049CountingOnes题目,介绍了一种有效的算法来计算从1到给定整数N中所有数字中1的个数。通过枚举低位到高位,计算每一位上1出现的次数,最终得到总数。提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1049 Counting Ones (30 分)

The task is simple: given any positive integer N, you are supposed to count the total number of 1’s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1’s in 1, 10, 11, and 12.

这道题没想出来,参考的 算法笔记上面的思想.从低位枚举到高位,计算每一位的出现1 的次数.

参考代码

#include <cstdio>
int res=0,num,i=1;
int left,right,now;
int main(){
    scanf("%d",&num);
    while(num/i){
        left =num/(i*10);
        now =num/i%10;
        right =num%i;
        if(now==0)  res+=left*i;
        else if(now ==1)  res+=left*i+1+right;
        else res+=(left+1)*i;
        i*=10;
    }
    printf("%d\n",res);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值