-
大数相加
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.length() - 1, j = num2.length() - 1, add = 0;
string ans = "";
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1[i] - '0' : 0;
int y = j >= 0 ? num2[j] - '0' : 0;
int result = x + y + add;
ans.push_back('0' + result % 10);
add = result / 10;
i -= 1;
j -= 1;
}
// 计算完以后的答案需要翻转过来
reverse(ans.begin(), ans.end());
return ans;
}
};
-
大数相乘
-
class Solution { public: void Add(string& ret, string temp, int index) { int len1 = ret.size(); int len2 = temp.size(); int i; int c = 0; for (i = index; i < len1; i++) { int a = ret[i] - '0'; int b = temp[i - index] - '0'; int sum = a + b + c; ret[i] = ((sum % 10) + '0'); c = sum / 10; } for (int j = i - index; j < len2; j++) { int a = temp[j] - '0'; int sum = a + c; ret.push_back((sum % 10) + '0'); c = sum / 10; } if (c) ret.push_back(c + '0'); } string multiply(string num1, string num2) { string ret; reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); if (num1 == "0" || num2 == "0") return "0"; int len1 = num1.size(); int len2 = num2.size(); for (int i = 0; i < len1; i++) { string temp; int a = num1[i] - '0'; int c = 0; for (int j = 0; j < len2; j++) { int b = num2[j] - '0'; int sum = a * b + c; temp.push_back((sum % 10) + '0'); c = sum / 10; } if (c) temp.push_back(c + '0'); Add(ret, temp, i); } reverse(ret.begin(), ret.end()); return ret; } };