| Run ID | 作者 | 问题 | 语言 | 测评结果 | 分数 | 时间 | 内存 | 代码长度 | 提交时间 |
|---|---|---|---|---|---|---|---|---|---|
| 436803 | 顾鑫辰 | 【C6-4】高精度减法2 | C++ | 解答错误 | 0 | 1 MS | 252 KB | 2502 | 2026-04-18 15:48:27 |
#include <iostream> #include <string> #include <algorithm> using namespace std; // 辅助函数1:比较两个无符号大数的大小 a >= b ? bool compare(string a, string b) { if (a.size() != b.size()) return a.size() > b.size(); return a >= b; } // 辅助函数2:高精度减法 a - b (保证a >= b,无符号) string sub(string a, string b) { string res; int borrow = 0; // 借位 // 逆序,从低位开始计算 reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); for (int i = 0; i < a.size(); i++) { // 当前位数字 int numA = a[i] - '0'; int numB = (i < b.size()) ? (b[i] - '0') : 0; numA -= borrow; // 减去上一位的借位 borrow = 0; if (numA < numB) { // 需要借位 numA += 10; borrow = 1; } res.push_back((numA - numB) + '0'); } // 去掉前导0(逆序后是末尾0) while (res.size() > 1 && res.back() == '0') { res.pop_back(); } // 逆序回来 reverse(res.begin(), res.end()); return res; } // 高精度减法主函数:a - b string bigSub(string a, string b) { // 拆分符号和数字 bool negA = (a[0] == '-'); bool negB = (b[0] == '-'); string numA = negA ? a.substr(1) : a; string numB = negB ? b.substr(1) : b; string res; // 情况1:a - b (都是正数) if (!negA && !negB) { if (compare(numA, numB)) { res = sub(numA, numB); } else { res = "-" + sub(numB, numA); } } // 情况2:-a - b = -(a + b) 这里统一用减法逻辑 else if (negA && !negB) { res = "-" + (compare(numA, numB) ? sub(numA, numB) : sub(numB, numA)); } // 情况3:a - (-b) = a + b 简化为 a + b else if (!negA && negB) { // 等价于加法,直接调用sub逻辑处理 if (compare(numA, numB)) { res = sub(numA, numB); } else { res = sub(numB, numA); } } // 情况4:-a - (-b) = b - a else { if (compare(numB, numA)) { res = sub(numB, numA); } else { res = "-" + sub(numA, numB); } } return res; } int main() { string s1, s2; // 输入两个高精度数 cin >> s1 >> s2; // 计算 s1 - s2 cout << bigSub(s1, s2) << endl; return 0; }