D e s c r i p t i o n Description Description
一天,小R准备找小h去游泳,当他找到小h时,发现小h正在痛苦地写着一列数,1,2,3,…n,于是就问小h痛苦的原因,小h告诉他,现在他要算1…n这些数里面,1出现的次数是多少,如n=11的时候,有1,10,11共出现4次1,现在给出n,你能快速给出答案么?
I n p u t Input Input
一行,一个整数n
O u t p u t Output Output
一个整数,表示1…n中1出现的次数。
S a m p l e Sample Sample I n p u t Input Input
11
S a m p l e Sample Sample O u t p u t Output Output
4
H i n t Hint Hint
对于30%的数据:n<=1000;
对于100%的数据:n<=maxlongint;
T r a i n Train Train o f of of T h o u g h t Thought Thought
就是把一个数的每一位分开来算
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#define ll long long
using namespace std;
const ll F[20] = {0, 1, 2, 21, 301, 4001, 50001, 600001, 7000001,
80000001, 900000001, 1000000001, 20000000001, 300000000001,
4000000000001, 50000000000001, 600000000000001, 7000000000000001,
80000000000000001, 900000000000000001};
ll Sum, n, Flag, l;
int A[55];
ll power_(int k)
{
ll num = 1;
for(int i = 1; i < k; ++i)
num *= 10;
return num;
}
int main()
{
scanf("%lld", &n);
while(n)A[++l] = n % 10, n /= 10;
for(int i = l; i >= 1; --i)
{
if(A[i] > 1)Sum += power_(i) - 1;
if(Flag)Sum += A[i] * power_(i);
if(A[i] == 1)Flag = 1;
if(A[i])Sum += A[i] * F[i] - A[i] + 1;
}
printf("%lld", Sum);
return 0;
}