题解 | #大数加法#
大数加法
https://www.nowcoder.com/practice/11ae12e8c6fe48f883cad618c2e81475
static const auto io_sync_off = []() { //lambda函数 // turn off sync,关闭输入输出流的缓存 std::ios::sync_with_stdio(false); // untie in/out streams,实现输入和输出流的解绑 std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; } (); class Solution { public: void add(string& s, string& t, int i, int j, char& carry, char& base) { //加法,引用达到更新进位和本位的作用 int num = s[i] - '0' + t[j] - '0' + carry - '0'; base = num % 10 + '0'; carry = num / 10 + '0'; } string solve(string s, string t) { if (s.size() < t.size())return solve(t, s); //保证第一个字符串长度不小于第二个字符串 int lo = s.size(), sh = t.size(); char carry = '0', base; //carry为进位,base为本位 for (int i = lo - 1, j = sh - 1; j >= 0; i--, j--) { //第一阶段 add(s, t, i, j, carry, base); s[i] = base; } string tmp = "0"; for (int i = lo - sh - 1; carry != '0'; i--) { //第二阶段,处理剩余进位 if (i < 0) { s.insert(0, "0"); i++; } add(s, tmp, i, 0, carry, base); s[i] = base; } return s; } };