C++ 将数字分成两个可整除的部分
在这个问题中,我们得到一个可以解释为数字的字符串。现在我们必须将该字符串分成两部分,使得第一部分可以被 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
现在在这个问题中,我们将进行一些预计算,这将使我们的程序更快,然后它将能够处理更高的约束。
查找解决方案的方法
在这种方法中,我们将通过字符串运行两个循环,第一个从开始到结束,第二个从结束到开始。现在在每个点,我们取在第一个循环中形成的整数与 a 的模,以及在第二个循环中与 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 的模。对于 b,我们运行一个后向循环并存储模,因为我们知道如果我们某个位置的 a 的模为零,并且下一个索引的 b 的模为零,那将是我们的答案,因此我们打印它。
结论
在本教程中,我们解决了一个问题,即查找将数字分成两个可整除的部分。我们还学习了这个问题的 C++ 程序以及我们解决此问题的完整方法(普通方法)。我们可以在其他语言(如 C、java、python 和其他语言)中编写相同的程序。我们希望您发现本教程有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP