题解 | #火星A+B#

火星A+B

https://www.nowcoder.com/practice/46bb070835e548678c78477f1fb0b92e

#include <bits/stdc++.h>
using namespace std;
int sushu[26];

vector<string> addString(vector<string> &s1,int i,vector<string> &s2,int j)
{
	int carry=0;
	vector<string> res;
	int k=1;
	while(i>=0&&j>=0)
	{
		int num=stoi(s1[i])+stoi(s2[j])+carry;
		res.push_back(to_string(num%sushu[k]));
		carry=num/sushu[k++];
		i--;j--;
	}
	while(i>=0)
	{
		int num=stoi(s1[i])+carry;
		res.push_back(to_string(num%sushu[k]));
		carry=num/sushu[k++];
		i--;
	}
	while(j>=0)
	{
		int num=stoi(s2[j])+carry;
		res.push_back(to_string(num%sushu[k]));
		carry=num/sushu[k++];
		j--;
	}
	while(carry!=0)
	{
		res.push_back(to_string(carry%sushu[k]));
		carry=carry/sushu[k++];
	}
	reverse(res.begin(),res.end());
	return res;
}

int main(){
	string str1,str2,s1,s2;
	int j=1;
	for(int i=2;j<=25;i++)
	{
		bool flag=true;
		for(int k=2;k<i;k++)
		{
			if(i%k==0){
				flag=false;
				break;	
			}
		}
		if(flag) sushu[j++]=i;
	}
	while(cin>>str1>>str2)
	{
		vector<string> s1(25),s2(25);
		int j=0;
		for(int i=0;i<str1.size();i++)
		{
			if(str1[i]!=',')	s1[j]+=str1[i];
			else	j++;	
		}
		int k=0;
		for(int i=0;i<str2.size();i++)
		{
			if(str2[i]!=',')	s2[k]+=str2[i];
			else	k++;
		}
		vector<string> res=addString(s1,j,s2,k);
		for(int i=0;i<res.size()-1;i++)
		{
			cout<<res[i]<<",";
		}
		cout<<res[res.size()-1]<<endl;
	}
	return 0;
}

全部评论

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务