题目
分析
需要考虑输入的两个加数的几种情况:位数多的+位数少的,位数相等进行相加,同时还需要考虑进位。最开始加完之后的数据用reverse反转,奇怪的是怎么都反转的不对(实际上看起来像是失效了),最后换成用字符数组处理。
代码
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
using namespace std;
int max_len(string s1, string s2) {
return s1.length() > s2.length() ? s1.length() : s2.length();
}
int main() {
string table, ls1, ls2;
char res[101]={};
map<char, int> mci; // 储存进制表
map<int, char> mic;
cin >> table;
cin >> ls1;
cin >> ls2;
reverse(ls1.begin(), ls1.end());
reverse(ls2.begin(), ls2.end());
for (int i = 0; i < table.length(); i++) {
mci[table[i]] = i; //转化成对应的键值对
mic[i] = table[i];
}
// for(auto it=mic.begin();it!=mic.end();it++)
// cout<<it->first<<" "<<it->second<<endl;
// for(auto it=mci.begin();it!=mci.end();it++)
// cout<<it->first<<" "<<it->second<<endl;
int jinwei = 0,cnt=0;
for (int i = 0; i < max_len(ls1, ls2); i++) {
if (i < ls1.length() && i < ls2.length()) {
int sum = mci[ls1[i]] + mci[ls2[i]] + jinwei;
if (sum >= table.length()) {
res[i] = mic[sum - table.length()];
// cout<<jinwei<<" "<<endl;
jinwei = 1;
cnt++;
}
else {
res[i] = mic[sum];
// cout<<mic[sum];
jinwei = 0;
cnt++;
}
}
else if (i < ls1.length() && i >= ls2.length()) {
int sum = mci[ls1[i]] + jinwei;
if (sum >= table.length()) {
res[i] = mic[sum - table.length()];
// cout<<mic[sum-table.length()]<<" "<<res[i]<<" "<<endl;
jinwei = 1;
cnt++;
}
else {
res[i] = mic[sum];
// cout<<mic[sum]<<" "<<res[i]<<" "<<i<<endl;
jinwei = 0;
cnt++;
}
}
else
// (i < ls2.length() && i >= ls1.length())
{
int sum = mci[ls2[i]] + jinwei;
if (sum >= table.length()) {
res[i] = mic[sum - table.length()];
// cout<<mic[sum-table.length()];
jinwei = 1;
cnt++;
}
else {
res[i] = mic[sum];
// cout<<mic[sum];
jinwei = 0;
cnt++;
}
}
}
if (jinwei != 0) { // 相加之后仍有余数,如999+111
res[++cnt] = mic[jinwei];
// cout<<mic[jinwei]<<" "<<jinwei<<endl;
cnt++;
}
// cout<<end(res)-begin(res)<<endl;
string s=" ";
for(int i=cnt;i>=0;i--)
if(res[i])
cout<<res[i];
return 0;
}
/*
case 1:
0123456789
999
111
case 2:
case 3:
*/