题解 | #又一版 A+B#
又一版 A+B
https://www.nowcoder.com/practice/9255c05d45b8406c9b588d7c57aa920b
本题由于数字过于大,足足有31位,所以只能用字符串处理,所以我们要学会两个函数的运用:字符串相加和字符串除。
针对字符串相加,有三个注意点:
1.相加的位置匹配是两个数字的最后一位,所以这里要两个指针分别指向两个数字的末尾。
2.在做完相加后,需要对较长的数字做处理,让最后的进位发挥效果。
3.最后的进位也要处理。
针对字符串除,可以看清这个代码形式,理解后会敲就行
#include <bits/stdc++.h> using namespace std; string add(string a, string b) { if (a.size() < b.size()) { //保证a是较长的 string temp = a; a = b; b = temp; } int plus = 0; int i = a.size() - 1; int j = b.size() - 1; while (j >= 0) { int current = plus + a[i] - '0' + b[j] - '0'; a[i] = current % 10 + '0'; plus = current / 10; i--; j--; } while (i >= 0) { int current = plus + a[i] - '0'; a[i] = current % 10 + '0'; plus = current / 10; i--; } if (plus != 0) { char num = plus + '0'; a = num + a; } return a; } int qiuyu(string sum, int m) { int remainder = 0; for (int i = 0; i < sum.size(); i++) { int current = remainder * 10 + sum[i] - '0'; sum[i] = current / m + '0'; remainder = current % m; } return remainder; } string divide(string sum, int m) { //字符串除 int remainder = 0; for (int i = 0; i < sum.size(); i++) { int current = remainder * 10 + sum[i] - '0'; sum[i] = current / m + '0'; remainder = current % m; } int pos = 0; while (sum[pos] == '0') pos++; return sum.substr(pos); } int main() { int m; string a, b; while (cin >> m) { if (m == 0) break; cin >> a >> b; string sum = add(a, b); vector<int> num; while (!sum.empty()) { num.push_back(qiuyu(sum, m)); sum = divide(sum, m); } for (int i = num.size() - 1; i >= 0; i--) { cout << num[i]; } cout << '\n'; } }