string baseChar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //便于将数字直接转成进制的字符 int base; //进制
string addString(string a, string b)//高精度加法 { string res; int alen = a.size(), blen = b.size(); if (alen > blen) swap(a, b), swap(alen, blen); //保证a长度一定小于b int i = 0; int sum; int numa, numb; bool flag = false; while (i != alen) { //先一直操作直到a的末尾 //将a,b对应位上的数字或字符转成数字 numa = isalpha(a[i]) ? a[i] - 'A' + 10 : a[i] - '0'; numb = isalpha(b[i]) ? b[i] - 'A' + 10 : b[i] - '0'; //sum存储当前位相加结果 sum = numa + numb + flag; //进位结束了,恢复flag状态 flag = false; res.push_back(baseChar[sum % base]); //将结果存进res中 if (sum >= base) { //需要进位 flag = true; } ++i; } //把剩下b的数字加进去 while (i != blen) { numb = isalpha(b[i]) ? b[i] - 'A' + 10 : b[i] - '0'; //记得处理可能出现的进位 sum = numb + flag; flag = false; res.push_back(baseChar[sum % base]); if (sum >= base) flag = true; ++i; } //b也结束了,但还需要进一位的话就进 if (flag) res.push_back('1'); return res; }
string addFunc(vector<string>& a)//实现累加 { string res = a[0]; int len = a.size(); for (int i = 1; i < len; i++) { res = addString(res, a[i]); } reverse(res.begin(), res.end()); //res是倒序的,反转一下 return res; }
intmain() { ios::sync_with_stdio(false); //关闭流同步大大提高cin效率 int w; cin >> w; cin >> base; string str; vector<string> a; int i = 0; while (w--) { cin >> str; int len = str.size(); while (i < len && str[i] == '0') ++i; //删去前导零 if (i) str.substr(i); i = 0; reverse(str.begin(), str.end()); //倒序存储 a.push_back(str); } cout << addFunc(a); return0; }