C++程序,用于删除数字字符串中的字符,使其能被8整除

2023年 8月 29日 45.9k 0

C++程序,用于删除数字字符串中的字符,使其能被8整除

Given a number in the form of a string, we need to find where to make it divisible by eight after deleting zero or more elements. In other words, we need to find whether there is a subsequence of the string, which is divisible by 8. Return the modified string or -1 if it is not possible.

根据可整除规则,任何最后三位数字可被8整除的数也可被8整除。例如,56992992和476360可被8整除,但2587788不能。如果结果是一个整数,则原始数可被8整除。

Let us look at some input scenarios that explain the method in detail −

如果传递给该方法的输入是包含任何可被8整除的子字符串的数字字符串,则在结果列表中我们可以获得可被8整除的子字符串−

Input: 2567992
Result: 56

登录后复制

如果输入给方法的是一个不包含任何可被8整除的子字符串的数字字符串,输出结果将返回为−

Input: 77777777777
Result: -1

登录后复制

Algorithm

  • 字符串输入被遍历,检查是否有任何子字符串是8的倍数。

  • If there is any consequent substring present in the input, the substring is returned as the output.

  • 如果找到子字符串,则程序终止,否则重复步骤2直到找到子字符串。

  • 如果输入中没有可被8整除的子字符串,则返回输出为-1。

Example

在下面的C++程序中,我们取两个字符串,一个可以转换为可被8整除的字符串,另一个不能,然后找出每种情况下的输出。我们可以从0到1000迭代,以8的倍数如0、8、16、24、32...1000,并检查这个数字是否作为给定字符串的子序列存在。

#include
using namespace std;
int checkIfSubstringExist(string req, string given) {
int index = 0;
for (char ch : given) {
if (req[index] == ch) {
index++;
}
}
return index == (int)req.size();
}
string solve(string s) {
for (int i = 0; i

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论