僅包含數字 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