幸運數字4和7,求l到r的幸運數字和

#牛客算法周練幸運數字2
鏈接:https://ac.nowcoder.com/acm/contest/5086/

定義一個數字爲幸運數字當且僅當它的所有數位都是4或者7。
比如說,47、744、4都是幸運數字而5、17、467都不是。
定義next(x)爲大於等於x的第一個幸運數字。給定l,r,請求出next(l) + next(l + 1) + … + next(r - 1) + next®。
輸入描述:
兩個整數l和r (1 <= l <= r <= 1000,000,000)。
輸出描述:
一個數字表示答案。

思路:一個一個來判斷肯定超時,我們直接把所有的幸運數字求出來,對於l,r我們直接在幸運數字中一段一段的進行判斷,例如l = 2,r = 7;那麼2-4都是4,4-7都是7;很明顯幸運數字一共也只有1000多個,所以直接一共循環就可以了。

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ll;
const ll M = 1e9;

ll a[1025];
int len = 0;

void dfs(ll x){
	a[len++] = x;
	ll y = x * 10 + 4;
	if(y > M) return;
	dfs(y);
	y = x * 10 + 7;
	dfs(y);
}
int main(){
	dfs(4);//兩個dfs用來處理幸運數字
	dfs(7);
	sort(a, a + len);
	a[len++] = 4444444444;//前面dfs中這個數沒有放入,對於大於777777777的數的答案應該是這個
	ll l,r;
	cin >> l >> r;
	ll res = 0;
	int f = 0;
	for(int i = 0; i < len; i++){
		if(l > a[i]) continue;//還沒到l,不用處理
		if(f == 0){
			if(r <= a[i]){
				res = (r - l + 1) * a[i];
				break;
			}
			res = res + (a[i] - l + 1) * a[i];
			f = 1;
			continue;
		}
		if(a[i] >= r){
			res = res + (r - a[i - 1]) * a[i];
			break;
		}
		else
		    res = res + (a[i] - a[i - 1]) * a[i]; 
	}
	cout << res << endl;
	return 0;
}

PS:第一次寫文章,兄弟們能否給點意見在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章