题目描述
正整数 A 的“DA(为 1 位整数)部分”定义为由 A 中所有 DA 组成的新整数 PA。例如:给定 8,DA=6,则 A的“6 部分”PA 是 66,因为 A 中有 2 个 6。
现给定 A、DA、B、DB,请编写程序计算 PA+PB。
输入格式:
输入在一行中依次给出 A、DA、B、DB,中间以空格分隔,其中 0。
输出格式:
在一行中输出 PA+PB 的值。
输入样例 1:
3862767 6 13530293 3
输出样例 1:
399
输入样例 2:
3862767 1 13530293 8
输出样例 2:
0
思路:用string来进行整数的输入,使用stringstream(头文件是<sstream>,这里bu不做介绍,想了解更多的话,这里有个大佬总结的不错https://blog.csdn.net/sunshineacm/article/details/78068987)流
来将string转换为int类型的数据进行相加最后输出。要注意有一个坑,这个数字串里没有其对应的数字时,其变换后应该为0.代码如下:
#include <iostream> #include <cstring> #include <algorithm> #include <string.h> #include <sstream> int const max_n = 1002; using namespace std; int main() { stringstream ss, tt; string a, b, c, d, aa, bb; cin >> a >> aa>> b >> bb; for (int i = 0, j = 0; i < a.length(); i++) { if (a[i] == aa[0])c+=aa; } for (int i = 0, j = 0; i < b.length(); i++) { if (b[i] == bb[0])d+=bb; } int as, bs; if (c.size() == 0) { as = 0; } else { ss << c; ss >> as; } if (d.size() == 0)bs = 0; else { tt << d; tt >> bs; } printf("%d\n", as + bs); return 0; }