幸运数字是正整数,其十进制表示形式仅包含幸运数字4和7。任务是查找具有等于n的数字之和的最小幸运数字。
如果总和= 22,则幸运数字为4477,因为4 + 4 + 7 + 7 = 22
1. If sum is multiple of 4, then result has all 4s. 2. If sum is multiple of 7, then result has all 7s. 3. If sum is not multiple of 4 or 7, then we can subtract one of them till sum becomes multiple of other.
#include <bits/stdc++.h>
using namespace std;
void luckyNumber(int sum) {
int a, b;
a = b = 0;
while (sum > 0) {
if (sum % 7 == 0) {
++b;
sum = sum - 7;
} else
if (sum % 4 == 0) {
++a;
sum = sum - 4;
} else {
++a;
sum = sum - 4;
}
}
cout << "Answer = ";
if (sum < 0) {
cout << "-1\n" << endl;
return;
}
for (int i = 0; i < a; ++i) {
cout << "4";
}
for (int i = 0; i < b; ++i) {
cout << "7";
}
cout << endl;
}
int main() {
int sum = 22;
luckyNumber(sum);
return 0;
}当您编译并执行上述程序时。它产生以下输出
输出结果
Answer = 4477