在这个问题中,我们得到了一个可以解释为数字的字符串。现在我们必须将该字符串划分为两部分,使得第一部分可被 A 整除,第二部分可被 B 整除(给我们的两个整数)。例如 -
Input : str = "123", a = 12, b = 3
Output : YES
12 3
"12" is divisible by a and "3" is
divisible by b.
Input : str = "1200", a = 4, b = 3
Output : YES
12 00
Input : str = "125", a = 12, b = 3
Output : NO
现在,在这个问题中,我们将进行一些预先计算,以使我们的程序更快,然后它将能够在更高的约束条件下工作。
寻找解决方案的方法
在这种方法中,我们将在字符串中运行两个循环,第一个循环从开始到结束,第二个循环从结束到开始。现在,在每个点,我们对第一个循环中的 an 和第二个循环中的 b 形成的整数取模,然后我们就可以找到答案。
示例
#include <bits/stdc++.h>
using namespace std;
void divisionOfString(string &str, int a, int b){
int n = str.length();
vector<int> mod_a(n+1, 0); //
mod_a[0] = (str[0] - '0')%a;
for (int i=1; i<n; i++) // front loop for calculating the mod of integer with a
mod_a[i] = ((mod_a[i-1]*10)%a + (str[i]-'0'))%a;
vector<int> mod_b(n+1, 0);
mod_b[n-1] = (str[n-1] - '0')%b;
int power10 = 10; // as we have assigned answer to last index
for (int i= n-2; i>=0; i--){ // end loop for calculating the mod of integer with b
mod_b[i] = (mod_b[i+1] + (str[i]-'0')*power10)%b;
power10 = (power10 * 10) % b;
}
for (int i=0; i<n-1; i++){ // finding the division point
if (mod_a[i] != 0) // we can skip through all the positions where mod_a is not zero
continue;
if (mod_b[i+1] == 0){ // now if the next index of mod_b is also zero so that is our division point
cout << "YES\n";
/*******Printing the partitions formed**********/
for (int k=0; k<=i; k++)
cout << str[k];
cout << " ";
for (int k=i+1; k < n; k++)
cout << str[k];
return;
}
}
cout << "NO\n"; // else we print NO
}
// Driver code
int main(){
string str = "123"; // given string
int a = 12, b = 3;
divisionOfString(str, a, b);
return 0;
}
输出
YES
12 3
上述代码的解释
在这种方法中,我们现在计算每次除法形成的数字的余数。我们的第一个数字应该可以被 a 整除,因此我们运行一个前向循环并用 a 存储该数字的 mod。对于 b,我们运行一个向后循环并现在存储 mod,因为我们知道,如果任何位置的 an 的 mod 为零,并且下一个索引的 b 的 mod 为零,这将是我们的答案,因此我们打印它。
结论
在本教程中,我们解决了一个问题,将一个数字分成两个可整除的部分。我们还学习了该问题的 C++ 程序以及解决该问题的完整方法(普通)。我们可以用其他语言比如C、java、python等语言来编写同样的程序。我们希望本教程对您有所帮助。