下面是一个解决此问题的 C++ 代码示例:
#include <iostream>
#include <string>
using namespace std;
bool checkDivisibleBy8(string num) {
int n = num.size();
if (n == 1) {
return stoi(num) % 8 == 0;
} else if (n == 2) {
int x = stoi(num);
return x % 8 == 0 || (x % 10 == 0 && x / 10 % 8 == 0);
}
int count[10] = {0};
for (char c : num) {
count[c - '0']++;
}
for (int i = 104; i < 1000; i += 8) {
int tempCount[10] = {0};
tempCount[i / 100]++;
tempCount[i / 10 % 10]++;
tempCount[i % 10]++;
bool valid = true;
for (int j = 0; j < 10; j++) {
if (tempCount[j] > count[j]) {
valid = false;
break;
}
}
if (valid)
return true;
}
return false;
}
string solve(string num) {
int n = num.size();
// Check if the original number is divisible by
// the target number without deleting any digits
if (checkDivisibleBy8(num))
return num;
// Iterate through all possible combinations of deleted digits
for(int i = n-1; i >= max(0, n-3); i--) {
string subNum = num.substr(0, i) + num.substr(i+1);
// Check if the modified number is divisible by 8
if (checkDivisibleBy8(subNum))
return subNum;
}
return "NO";
}
int main() {
string num;
cin >> num;
string result = solve(num);
if (result != "NO") {
cout << "YES" << endl;
cout << result << endl;
} else {
cout << "NO" << endl;
}
return 0;
}
这段代码首先定义了一个名为 checkDivisibleBy8 的函数,用于检查一个给定的字符串表示的数字是否能被 8 整除。然后定义了一个 solve 函数,用于解决题目中的问题。
在 main 函数中,首先读取输入的数字 num,然后调用 solve 函数得到结果。如果结果不是 “NO”,则输出 “YES” 和最终得到的数;否则输出 “NO”。
请注意,在处理大整数时可能会遇到溢出问题,这需要额外考虑和处理。此示例代码假设输入范围在有效限制内,并且没有进行溢出检查。
内容由零声教学AI助手提供,问题来源于学员提问




