1049 Counting Ones

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.

Input Specification:

Each input file contains one test case which gives the positive N (≤2^30).

Output Specification:

For each test case, print the number of 1’s in one line.

Sample Input:

12

Sample Output:

5

参考解析:

https://blog.csdn.net/yu121380/article/details/89021387

题意分析:

(1)给出一正整数N,求从1到N之间的所有数当中含有1的个数

(2)此题最容易想到的是从1到N遍历,求每个数中包含1的个数,但这样在数字比较大时,肯定超时。如果不遍历,那要怎么去求呢?这就需要寻找数学规律了。我们先从每一位开始:求当某个位置为1时共有有多少个数.以百为为例,如12145、12045、12145.即可能存在三种情况:(我们求的是某位为1的情况,如百位100~199,就不考虑101了,因为在个位和十位就已经求过了,有叠加,这点不好理解,仔细想想)

①若此数百位本身就等于1,如12145,则大于等于100的有100199、11001199、21002199…、1110011199,另外还有12100~12145;所以当百位为1时,分高位部分和低位部分,即百位为1的数有12*100+45+1个;

②若百位等于0,如12045,则大于等于100的有100199、11001199、21002199…、1110011199,即百位为1的数有12*100个

③若百位大于1,则12345,则大于等于100的有100199、11001199、21002199…、1110011199、12100、12199,即百位为1的数有(12+1)*100个

(3)然后按照此思路同样去求其他位置为1的个数

//
//  main.cpp
//  1049 Counting Ones
//
//  Created by 月文 陈  on 2021/3/4.
//

#include <iostream>
using namespace std;

int main(int argc, const char * argv[]) {
    int N;
    cin>>N;
    int count=0;
   
    int indexLeftNum,indexRightNUm,index;
    int i=1;//代表数位
    while(N/i!=0){
        index=(N/i)%10;
        indexLeftNum=(N/i)/10;
        indexRightNUm=N-(N/i)*i;
        
        if(index==1)     count+=i*indexLeftNum+indexRightNUm+1;
        else if(index>1) count+=i*(indexLeftNum+1);
        else             count+=i*indexLeftNum;
        
        i*=10;
    }
    cout<<count<<endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值