这个题目是高精度题目,所以很自然的选择字符串来写,但是模拟我感觉我没怎么用到,可能有其他算法吧,我采用的是分治,代码量有点大,如果有比较好的写法,还请多多指正。
#include"iostream"
#include"string"
#include"map"
using namespace std;
map<char, int> mp = { {'0',0},{'1',1},{'2',2},{'3',3},{'4',4},{'5',5},{'6',6},{'7',7},{'8',8},{'9',9}, {'A',10},{'B',11},{'C',12},{'D',13},{'E',14},{'F',15} };
map<int,char> mf = { {0,'0'},{1,'1'},{2,'2'},{3,'3'},{4,'4'},{5,'5'},{6,'6'},{7,'7'},{8,'8'},{9,'9'},{10,'A'},{11,'B'},{12,'C'},{13,'D'},{14,'E'},{15,'F'} };
bool is_Caror(string a) {
for (int i = 0, j = a.size() - 1;i < j;i++,j--) {
if (a[i] != a[j])return false;
}
return true;
}
void sum(string a, string& b, int mark) {
string::iterator home = a.begin(), away = a.end() - 1;
int bao, flag = 0;//bao is the adder number for the title;
while (home != a.end() && away >= a.begin()) {
bao = mp[*home] + mp[*away]+flag;
flag=0;
if(bao>=mark){
bao%=mark;
flag=1;
}
b.push_back(mf[bao]);
home++,away--;
}
if(flag!= 0)b.push_back('0' + flag);
}
int main() {
int mark,i;
string a;
cin>>mark>>a;
for (i = 1;i <= 30;i++) {
if (is_Caror(a))break;
string temp;
sum(a, temp, mark);
a = temp;
}
if (i <= 30)cout <<"STEP="<< i-1 << endl;
else cout << "Impossible!" << endl;
return 0;
}
本章到此结束!谢谢观赏