链接: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)。
输出描述:
一个数字表示答案。
输入
2 7
输出
33
思路:
这道题可以用打表记录下所有的幸运数字,再在l到r这个区间去遍历就好。
代码
#include<iostream>
#include<map>
#include<queue>
using namespace std;
const long long ma = 5000000000;
long long ant=0,ans=0;
long long s[100005];
long long l,r;
map<long long,long long>mp;
void da(){
queue<long long>q;
q.push(4);
q.push(7);
while(!q.empty()){
long long x=q.front();
q.pop();
s[++ant]=x;
if(x*10+4<=ma&&!mp[x*10+4]){
q.push(x*10+4);
mp[x*10+4]=1;
}
if(x*10+7<=ma&&!mp[x*10+7]){
q.push(x*10+7);
mp[x*10+7]=1;
}
}
}
int main(){
da();//打表用s数组记录4-ma中所有的幸运数字
cin>>l>>r;
for(int i=1;i<=ant;i++){
if(s[i]>=l){
if(s[i]<=r){
ans+=(s[i]-l+1)*s[i];//最小区间长度乘对应的幸运数字则为这个区间幸运数值的和
l=s[i]+1;
}
else{
ans+=(r-l+1)*s[i];//最小区间长度乘对应的幸运数字则为这个区间幸运数值的和
l=r+1;
}
}
if(l>r){//若l>r,则遍历结束,输出答案
cout<<ans;
return 0;
}
}
return 0;
}


京公网安备 11010502036488号