4.8 每日一题题解

幸运数字Ⅱ

###涉及知识点:

  • 预处理/打表

###solution:

  • \(由于l,r<=1e9,所以直接暴力会超时\)
  • $通过打表发现,小于等于1e9,满足每一位要么是4、要么是7的数字个数其实很少,我们可以直接枚举所有符合的数字4 , 7 , 47 , 74..... $
  • \(如何枚举,直接写个dfs\)
  • \(最后打表得出小于等于1e9且满足条件的数总计1022个\)
  • \(将打表的数字排个序,扫一遍就好了\)

###std:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
ll a[10005];
int cnt = 0;
void dfs(ll x,int len,int k){
    if(len == k){
        a[++cnt] = x;
        return ;
    }
    dfs(x*10 + 4, len + 1, k);
    dfs(x*10 + 7, len + 1, k);
}
int main()
{
    int l ,r;
    cin>>l>>r;
    for(int i=1;i<=10;i++){
        dfs(0 , 0 , i);
    }
    sort(a+1,a+1+cnt);
    ll ans = 0;
    for(int i=1;i<=cnt;i++){
        if(a[i] >= l){
            if(a[i] >= r){
                ans += 1ll*a[i]*(r-l+1);
                break ;
            }
            else
                ans += 1ll*a[i]*(a[i]-l+1),l = a[i] + 1;
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/QFNU-ACM/p/12658348.html
4.8
今日推荐