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 (<=230).

Output Specification:

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

Sample Input:
12
Sample Output:
5

给定一个正整数n,求1到n中所有数所含的1的个数。这里的思路是对数的每一位分析,假设某一位为1时,有多少种可能,然后相加得到结果。比如32104,对于0的那一位,大于31119的数在该位都不会出现1,观察311,1,9,容易知该位为1的可能为有312*10种(左边和右边都可以为0,所以是(311+1)*(9+1));对于1的那一位,首先大于32099该位为1的可能有5种,然后小于等于32099的情况和上面0的情况一样(32*100种),把两种情况得到的数相加即可;对于2的那一位,大于31999的数在该位不会出现1,观察3,1,999,容易知该位为1的可能有4*1000种。按照在以上思路对n的每一位进行计算然后累加即可得到答案。为了方便处理每一位,输入的格式设为字符串。


代码:

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
using namespace std;

int main()
{
    string n;
    cin>>n;
    int res=0;
    for(int i=0;i<n.size();i++)
    {
        int mid=n[i]-'0';
        int left=atoi(n.substr(0,i).c_str());
        int right=atoi(n.substr(i+1,n.size()).c_str());
        int ex=n.size()-i-1;
        if(mid==0) res+=left*pow(10,ex);
        else if(mid==1) res+=((right+1)+left*pow(10,ex));
        else res+=(left+1)*pow(10,ex);
    }
    cout<<res;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值