1 条题解
-
0
【本题解由站长编写】
高精度加法,可能含负数。用字符串存数,先比较绝对值:同号直接相加、异号则大减小再按差的正负决定输出符号。逐位用竖式处理进位/借位即可。
代码(C++17)
#include <bits/stdc++.h> using namespace std; string addAbs(const string &a, const string &b) { string res; int i = (int)a.size() - 1, j = (int)b.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry) { int s = carry; if (i >= 0) s += a[i--] - '0'; if (j >= 0) s += b[j--] - '0'; res.push_back(char('0' + s % 10)); carry = s / 10; } while (res.size() > 1 && res.back() == '0') res.pop_back(); reverse(res.begin(), res.end()); return res; } string subAbs(const string &a, const string &b) { // 保证 a >= b string res; int i = (int)a.size() - 1, j = (int)b.size() - 1, borrow = 0; while (i >= 0) { int s = a[i--] - '0' - borrow; if (j >= 0) s -= b[j--] - '0'; if (s < 0) { s += 10; borrow = 1; } else borrow = 0; res.push_back(char('0' + s)); } while (res.size() > 1 && res.back() == '0') res.pop_back(); reverse(res.begin(), res.end()); return res; } int main() { string a, b; cin >> a >> b; bool na = a[0] == '-', nb = b[0] == '-'; if (na) a = a.substr(1); if (nb) b = b.substr(1); string res; if (na == nb) { res = addAbs(a, b); if (na && res != "0") res = "-" + res; } else if (a.size() > b.size() || (a.size() == b.size() && a >= b)) { res = subAbs(a, b); if (na && res != "0") res = "-" + res; } else { res = subAbs(b, a); if (!na && res != "0") res = "-" + res; } cout << res << endl; return 0; }
- 1
信息
- ID
- 4241
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 6
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者