幸运数字Ⅱ
幸运数字Ⅱ
https://ac.nowcoder.com/acm/problem/15291
链接:https://ac.nowcoder.com/acm/problem/15291
题目描述:
定义一个数字为幸运数字当且仅当它的所有数位都是4或者7。 比如说,47、744、4都是幸运数字而5、17、467都不是。 定义next(x)为大于等于x的第一个幸运数字。给定l,r,请求出next(l) + next(l + 1) + ... + next(r - 1) + next(r)。
输入描述:
两个整数l和r (1 <= l <= r <= 1000,000,000)。
输出描述:
一个数字表示答案。
solution:
用深搜或宽搜先把4,7的所有排列找出来,然后进行排序,在对各个区间进行求和
#include<bits/stdc++.h>
using namespace std;
long long sum=0,l,r;
long long a[100010],cnt=0;
void dfs(long long x)
{
if(x>5000000000)return;
a[cnt++]=x;
dfs(x*10+4);
dfs(x*10+7);
}
int main()
{
cin>>l>>r;
dfs(0);
sort(a,a+cnt);
while(l<=r)
{
long long pos=lower_bound(a,a+cnt,l)-a;
if(a[pos]<=r)
sum=sum+(a[pos]-l+1)*a[pos];
else
sum=sum+(r-l+1)*a[pos];
l=a[pos]+1;
}
cout<<sum;
}

