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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章