给你一个数字n,要你求0-n中有多少个数字包含49,用n-不含49的个数即答案。
#include<bits\stdc++.h>
using namespace std;
typedef long long ll;
ll dp[20][10];//记录在i位,前一位是j的符合条件的个数
int a[20];//
ll dfs(ll pos,ll pre,ll lim)//当前的位置,前一位数,前一位是否是前一位的最大数
{
if(pos==-1) return 1;//此时已经将所有位置枚举完了,符合要求;
if(!lim&&dp[pos][pre]!=-1)
return dp[pos][pre];
int up=lim?a[pos]:9;//up表示能枚举的最大数字
ll ans=0;
for(int i=0;i<=up;i++)
{
if(pre==4&&i==9)
continue;
ans+=dfs(pos-1,i,lim&&i==up);//如果当前位置还没有达到最大数,则下一位的数没有限制。
}
if(!lim) dp[pos][pre]=ans;//保存当前状态符合要求的数
return ans;
}
ll solve(ll n)
{
int i=0;
while(n)
{
a[i++]=n%10;
n/=10;
}
return dfs(i-1,0,1);
}
int main()
{
int t;
scanf("%d",&t);
memset(dp,-1,sizeof(dp));
while(t--)
{
ll n;
scanf("%I64d",&n);
printf("%I64d\n",n-solve(n)+1);
}
return 0;
}