Day1 jzoj 1535. easygame

Description

一天,小R准备找小h去游泳,当他找到小h时,发现小h正在痛苦地写着一列数,1,2,3,…n,于是就问小h痛苦的原因,小h告诉他,现在他要算1..n这些数里面,1出现的次数是多少,如n=11的时候,有1,10,11共出现4次1,现在给出n,你能快速给出答案么?

Input

一行,就是n,(1<=n<=maxlongint)

Output

一个整数,表示1..n中1出现的次数。

Sample Input

11

Sample Output

4

做法:逐位讨论对答案的贡献:
{
当前位大于 1 : 只跟前面的数有关;
当前位小于等于1 :跟前面和后面的数都有关;
}

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#define ll long long
#define rep(i,a,b)  for (int i = a; i <= b; i++)
using namespace std;
ll n, f[16];

int main()
{
    cin >> n;
    ll p = n;
    int  now = 1; 
    ll len = 10;
    ll ans = 0;
    f[1] = 1;
    rep(i, 2, 14)
    f[i] = f[i - 1] * 10;
    while (p > 0)
    {
        int x = p % 10;
        int y = p / 10;
        if  (x > 1)  ans += ((y + 1) * f[now]);
        else if     (x == 1)    ans += (y * f[now]) + n % (len / 10) + 1;
        else if (x == 0)    ans += (y * f[now]);
        p /= 10;
        len *= 10;
        now++;
    }
    cout << ans;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章