1049 Counting Ones (30分)(数论)

题目

https://pintia.cn/problem-sets/994805342720868352/problems/994805430595731456

题意

找出1-n中1出现的个数

Sample Input:

12

Sample Output:

5

思路

参考从1到n整数中1出现的次数:O(logn)算法

则:
若weight为0,则1出现次数为round*base
若weight为1,则1出现次数为round*base+former+1
若weight大于1,则1出现次数为round*base+base

code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll inff=0x3f3f3f3f3f3f3f3f;
int N;
int ans=0;
int main()
{
    cin>>N;
    int temp=0;
    int left=0;
    int a=1;
    while(N)
    {
        int now=N%10;
        N/=10;
        ans+=N*a;
        if(now==1) ans+=(temp+1);
        if(now>1) ans+=a;
        temp+=(a*now);
        a*=10;
    }
    cout<<ans<<endl;
    return 0;
}

posted @ 2020-09-03 21:39  liuyongliu  阅读(163)  评论(0编辑  收藏  举报