1016. 部分A+B (15)
正整數A的“DA(爲1位整數)部分”定義爲由A中所有DA組成的新整數PA。例如:給定A = 3862767,DA = 6,則A的“6部分”PA是66,因爲A中有2個6。
現給定A、DA、B、DB,請編寫程序計算PA + PB。
輸入格式:
輸入在一行中依次給出A、DA、B、DB,中間以空格分隔,其中0 < A, B < 1010。
輸出格式:
在一行中輸出PA + PB的值。
輸入樣例1:3862767 6 13530293 3輸出樣例1:
399輸入樣例2:
3862767 1 13530293 8輸出樣例2:
0 解題思路: ·此題的關鍵在於如何計算新整數Pa,Pb,因爲A和B範圍太大,所以用字符串儲存 ·使用臨時變量temp更新其結果,遍歷字符串,如遍歷字符串A時,與Pa比較,如果相同即更新temp的值,遍歷完畢即Pa的值
#include <iostream>
#include <string>
using namespace std;
int solve(string a, int x)//函數用於計算Pa和Pb的值
{
int temp = 0;
for ( int i = 0; i<a.length(); i++ )
{
if ( a[i]-'0' == x )//因爲a爲字符串, 比較時應將其轉換爲數字進行比較
{
temp = x + temp*10;//條件成立更新temp的值
}
}
return temp;
}
int main()
{
string A, B;
int Da, Db, Pa, Pb;
cin >> A >> Da >> B >> Db;
Pa = solve(A, Da);
Pb = solve(B, Db);
cout << Pa + Pb << endl;
return 0;
}