洛谷: P1581 A+B Problem(升级版)

题目链接: P1581 A+B Problem(升级版) - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

思路:

注意事项: 万位可能有两位,所以在输入的时候要进行一些处理。

flag: 当前是往a里面放还是b里面放,遇到+的时候flag改变,表明该装a了。

hasNum:前面是否已经读到数字了。为了解决一位上出现多个数字的情况。 

不过这道题只有万位可能出现两个数字,所以开辟数组来解决这个问题(如题解)更简洁。

这样:

if(index<=4) a[index]=s[i]-'0';
else a[4]+=(s[i]-'0')*10;

其他就是细心问题了...(其实错了好几次,才发现ad函数少写了一个return,快折磨疯了ε=(´ο`*))))

#include <bits/stdc++.h>
int jw[6] = { 2,3,5,7,11,13 };
using namespace std;
vector<int> ad(vector<int> a,vector<int> b) {
	if (a.size() < b.size()) return ad(b, a);
	vector<int> c;
	int res = 0;
	for (int i = 0; i < a.size(); i++) {
		res += a[i];
		if (i < b.size()) res += b[i];//当前是个位
		c.push_back(res %jw[i]);
		res /= jw[i];
	}
	if (res) {
		c.push_back(res);
	}
	return c;
}
int main() {
	ios::sync_with_stdio(false);
	string s;
	cin >> s;
	vector<int> a, b;
	int flag = 1;
	int num = 0, hasNum = 0;
	for (int i = s.size() - 1; i >= 0; i--) {
		//如果是数字
		if (isdigit(s[i])) {
			if (!hasNum) {
				num = s[i] - '0';
				hasNum = 1;
			}
			else {
				num = 10 * (s[i] - '0') + num;
			}
		}
		else if (s[i] == ',') {
			hasNum = 0;
			if (flag) {
				b.push_back(num);//将数字送进去
			}
			else {
				a.push_back(num);
			}
		}
		else if(s[i]=='+') {
			hasNum = 0;
			b.push_back(num);
			flag = 0;
		}
	}
	a.push_back(num);
	vector<int> c = ad(a, b);
	for (int i = c.size()-1; i >= 0; i--) {
		cout << c[i];
		if (i > 0) cout << ",";
	}
	return 0;
}

成功AC:

posted @ 2024-02-21 13:48  YuKiCheng  阅读(41)  评论(0编辑  收藏  举报  来源