仅包含数字 4 和 7 且给定总和的最低数字,使用 C++
问题陈述
幸运数字是十进制表示中仅包含幸运数字 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP