PAT (Basic Level) Practice (中文)1016 部分A+B (15分)

正整数 A 的“D​A​​(为 1 位整数)部分”定义为由 A 中所有 D​A​​ 组成的新整数 P​A​​。例如:给定 A=3862767,D​A​​=6,则 A 的“6 部分”P​A​​ 是 66,因为 A 中有 2 个 6。

现给定 A、D​A​​、B、D​B​​,请编写程序计算 P​A​​+P​B​​。

输入格式:

输入在一行中依次给出 A、D​A​​、B、D​B​​,中间以空格分隔,其中 0<A,B<10​10​​。

输出格式:

在一行中输出 P​A​​+P​B​​ 的值。

输入样例 1:

3862767 6 13530293 3

输出样例 1:

399

输入样例 2:

3862767 1 13530293 8

输出样例 2:

0

实现代码:

#include <iostream>
#include<string>
using namespace std;
int f(string str, int n) {
	int sum = 0;
	for (int i = 0; i < str.length(); i++) {
		if (str[i] - '0' == n) {
			sum = sum * 10 + n;
		}
	}
	return sum;
}
int main(void) {
	string str1, str2;
	int a, b;
	cin >> str1 >> a >> str2 >> b;
	cout << f(str1, a) + f(str2, b);
}
原创文章 165 获赞 197 访问量 8万+

猜你喜欢

转载自blog.csdn.net/weixin_43751983/article/details/105425240