本文最后更新于:2021年4月13日 晚上
给定两个字符串形式的非负整数 num1
和num2
,计算它们的和。
提示:
num1
和num2
的长度都小于 5100
num1
和num2
都只包含数字 0-9
num1
和num2
都不包含任何前导零
- 你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: string addStrings(string num1, string num2) { int n1 = num1.size(); int n2 = num2.size(); if (n1 == 0 || n2 == 0) return n1 ? num1 : num2;
string num; int i = n1 - 1, j = n2 - 1, carry = 0; while (i >= 0 || j >= 0) { int a = (i >= 0) ? (num1[i--] - '0') : 0; int b = (j >= 0) ? (num2[j--] - '0') : 0; int sum = (a + b) + carry; carry = sum / 10; num.insert(0, to_string(sum % 10)); } if (carry) num.insert(0, to_string(carry)); return num; } };
|
拓展:字符串相减
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <iostream> #include <algorithm> using namespace std;
string sub(string& a, string& b) { string res = ""; int borrow = 0; int i = a.size()-1, j = b.size()-1; while (i >= 0 || j >= 0) { int x = i >= 0 ? (a[i] - '0') : 0; int y = j >= 0 > (b[j] - '0') : 0; int z = (x - borrow - y + 10) % 10; res += to_string(z); borrow = x - borrow - y < 0 ? 1 : 0; i--, j--; } reverse(res.begin(), res.end()); int pos = 0; while (pos < res.size()-1) { if (res[pos] != '0') break; } return res.substr(pos); }
bool cmp(string& a, string& b) { if (a.size() == b.size()) return a < b; return a.size() < b.size(); }
string subString(string& num1, string& num2) { string res; if (cmp(num1, num2)) { res = sub(num1, num2); if (res != "0") res.insert(0, "-"); } else res = sub(num1, num2); return res; }
int main() { string a, b; cin >> a >> b; cout << subString(a, b) << endl; return 0; }
|