51 Nod 1009 数字1的数量

1009 数字1的数量 

基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题

 收藏

 关注

给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的个数。

例如:n = 12,包含了5个1。1,10,12共包含3个1,11包含2个1,总共5个1。

Input

输入N(1 <= N <= 10^9)

Output

输出包含1的个数

Input示例

12

Output示例

5

 


#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
int ans=0;
int a[10];
ll mypow(int a,int b)
{
    ll res=1;
    for(int i=0;i<b;i++)res*=a;
    return res;
}
ll f(int pos1,int pos2)
{
    int len=pos2-pos1+1;
    ll res=0;int cnt=1;
    for(int i=pos1;i<=pos2;i++)res+=a[i]*mypow(10,len-(cnt++));
   return res;
}
int main()
{
   //freopen("in.txt","r",stdin);
    ll N;
    cin>>N;
    ll len=0;
    ll t=N;
    while(t>0)
    {
        t/=10;len++;
    }
    if(len==1){cout<<1<<endl;return 0;}
    else
    {
        t=N;int pos=len-1;
        while(t>0)
        {
            a[pos--]=t%10;
            t/=10;
        }

        if(a[0]==1)ans=(f(1,len-1)+1);
            else ans=mypow(10,len-1);
        for(int i=1;i<len;i++)
        {
            if(a[i]==0)
            {
                ans+=(f(0,i-1))*mypow(10,len-i-1);
            }
            if(a[i]==1)
            {
                ans+=(f(0,i-1)*mypow(10,len-i-1));
                ans+=(f(i+1,len-1)+1);
            }
            if(a[i]>1)
            {
                ans+=(f(0,i-1)+1)*mypow(10,len-i-1);
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值