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