给两个非常大的数,求出它们的和,差,积
典型的大数运算,大数乘法原理,做了不少题了,不过减法还是第一次遇到,稍微总结一下需要注意的点:
- 将可能出现负数的减法运算提前判断符号,转化为大数减小数。
- 减法如果某一位相减得到一个大于等于0的数,那么借位标志也要清零。
int main() {
string s1, s2;
while (cin >> s1 >> s2) {
ll sign = 1;
//将可能出现负数的减法提前判断符号,转化为大数减小数
if (s1.size() < s2.size())swap(s1, s2), sign = -1;
else if (s1.size() == s2.size() && s1 < s2)swap(s1, s2), sign = -1;
string sum, minus, mul; ll res = 0, mod = 0, l1 = s1.size(), l2 = s2.size();
reverse(s1.begin(), s1.end());
reverse(s2.begin(), s2.end());
for (int i = 0; i < l2; i++) {
res = mod + s1[i] - '0' + s2[i] - '0';
sum += (res % 10) + '0'; mod = res / 10;
}
for (int i = l2; i < l1; i++) {
res = mod + s1[i] - '0';
sum += (res % 10) + '0'; mod = res / 10;
}
if (mod > 0)sum += mod + '0'; mod = 0;
reverse(sum.begin(), sum.end());
for (int i = 0; i < l2; i++) {
ll res = mod + s1[i] - '0';
if (res >= s2[i] - '0')minus += (res - (s2[i] - '0')) + '0', mod = 0;
else minus += (res + 10 - (s2[i] - '0')) + '0', mod = -1;//借位
}
for (int i = l2; i < l1; i++) {
ll res = mod + s1[i] - '0';
if (res >= 0)minus += res + '0', mod = 0;//这一位>0,借位标志要清零
else minus += '9', mod = -1;
}
while (minus[minus.size() - 1] == '0')minus.pop_back();
reverse(minus.begin(), minus.end());
vec v1, v2, v3(l1 + l2 - 1); mod = 0;
for (int i = 0; i < l1; i++)v1.push_back(s1[i] - '0');
for (int i = 0; i < l2; i++)v2.push_back(s2[i] - '0');
for (int i = 0; i < l1; i++)
for (int j = 0; j < l2; j++)
v3[i + j] += v1[i] * v2[j];
for (int i = 0; i < l1 + l2 - 1; i++) {
ll res = v3[i] + mod;
v3[i] = res % 10; mod = res / 10;
}
while (mod > 0)v3.push_back(mod % 10), mod /= 10;
cout << sum << endl;
if (sign == -1)cout << '-';
cout << minus << endl;
for (int i = v3.size() - 1; i >= 0; i--)cout << v3[i];
cout << endl;
}
}