The counter-terrorists found a time bomb in the dust. But this time the terrorists improve on the time bomb. The number sequence of the time bomb counts from 1 to N. If the current number sequence includes the sub-sequence “49”, the power of the blast would add one point.
Now the counter-terrorist knows the number N. They want to know the final points of the power. Can you help them?
Input
The first line of input consists of an integer T (1 <= T <= 10000), indicating the number of test cases. For each test case, there will be an integer N (1 <= N <= 2^63-1) as the description.
The input terminates by end of file marker.
Output
For each test case, output an integer indicating the final points of the power.
Sample Input
3
1
50
500
Sample Output
0
1
15
Hint
From 1 to 500, the numbers that include the sub-sequence “49” are “49”,“149”,“249”,“349”,“449”,“490”,“491”,“492”,“493”,“494”,“495”,“496”,“497”,“498”,“499”,
so the answer is 15.
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <cstring>
using namespace std;
typedef long long ll;
ll dp[110][2], x[110];//x保存数的每一位
ll v[110];
ll n;
ll dfs(int pos, int pre, int state, bool limit)//第pos位,上一位的数字,上一位是否为4,是否到达上限
{
ll sum = 0;
if (pos == -1)//这个数枚举完了
return 0; //返回1表示是合法的
if (!limit && dp[pos][state] != -1)//记忆化
return dp[pos][state];
int up = (limit ? x[pos] : 9);//根据limit确定上限
for (int i = 0; i <= up; i++)//枚举,把不同情况的个数加到sum
{
if (pre == 4 && i == 9)
sum += limit ? n % v[pos] + 1 : v[pos];
else
sum += dfs(pos - 1, i, i == 4, limit && i == x[pos]);//递归
}
if(!limit)//记录状态
dp[pos][state] = sum;
return sum;
}
ll f(ll t)
{
int pos = 0;
memset(dp, -1, sizeof dp);
while (t)//提取每一位
{
x[pos++] = t % 10;
t /= 10;
}
return dfs(pos - 1, -1, 0, true);//从最高位开始递归
}
int main(void)
{
v[0] = 1;
for (int i = 1; i <= 20; i++){
v[i] = v[i - 1] * 10;
}
//memset(dp, -1, sizeof(dp));
int t;
scanf("%d", &t);
while (t--)
{
scanf("%lld", &n);
printf("%lld\n", f(n));
}
return 0;
}