幸运数字Ⅱ(打表+思路)

119 篇文章 1 订阅
113 篇文章 1 订阅

题目链接:幸运数字Ⅱ

思路:
打表你会发现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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值