题目链接:幸运数字Ⅱ
思路:
打表你会发现1e9以内的数,有1022个幸运数,将他们存入数组即可。
然后查找每一个数的next(l)的值(我们这里是按幸运数来计算的,不需要遍历所有的数)。
打印幸运数的思路:因为只有4和7,所以先记录4,和7,并放入队列中,从队列中取一个数,将它分别乘以4和7,小于1e9的记录并放入队列中,直到队列为空为止,最后要加入4444444444,因为例如1e9的next值为4444444444(upper_bound()会查找到),从小到大排序即可。(因为next的特性,所以只能用upper_bound())
下面是代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e4+9;
ll cun[maxn];
int doo()//打表记录每一个幸运数
{
queue<ll>q;
cun[0]=(ll)4;
cun[1]=(ll)7;
while(!q.empty())q.pop();
int len=2;
q.push(cun[0]);
q.push(cun[1]);
while(!q.empty())
{
ll x=q.front();
q.pop();
if(x*10+4<1e9)
{
cun[len++]=x*10+4;
q.push(x*10+4);
}
if(x*10+7<1e9)
{
cun[len++]=x*10+7;
q.push(x*10+7);
}
}
return len;
}
int main()
{
ll a,b;
int len=doo();
cun[len++]=4444444444;
sort(cun,cun+len);//从小到大排序
while(~scanf("%lld%lld",&a,&b))
{
int i=upper_bound(cun,cun+len,a)-cun;//查找离a,最近的幸运值
if(cun[i-1]==a)//有可能a就是一个幸运值,所以i--;
i--;
ll sum;
if(cun[i]<=b)//判断[a,b]中有没有幸运值
sum=(cun[i]-a+1)*cun[i];
else
{
sum=(b-a+1)*cun[i];
printf("%lld\n",sum);
continue;
}
for(i++; cun[i]<=b; i++)//通过幸运值跳着查找。
sum+=(cun[i]-cun[i-1])*cun[i];
if(cun[i]>b&&cun[i-1]!=b)//如果b不是一个幸运值
sum+=(b-cun[i-1])*cun[i];
printf("%lld\n",sum);
}
return 0;
}