classLongInt { public: staticconstexprint M = 1e9; // M进制分段,每段9位 vector<int> vd; // vd逆向保存结果 LongInt() {} LongInt(int a) { while (a > 0) { vd.push_back(a % M); a /= M; } } LongInt(longlong a) { while (a > 0) { vd.push_back(a % M); a /= M; } } LongInt(const string& num) { for (int i = num.size(); i > 0; i -= 9) { int start = max(0, i - 9); string chunkStr = num.substr(start, i - start); vd.push_back(stoi(chunkStr)); } }
string getString(){ string result; for (int i = vd.size() - 1; i >= 0; --i) { string chunkStr = to_string(vd[i]); if (i != vd.size() - 1) { // 补前导零,确保每段都是 9 位 chunkStr.insert(0, 9 - chunkStr.size(), '0'); } result += chunkStr; } return result; } voidoutput(){ if (vd.empty()) printf("0"); else { printf("%d", vd.back()); for (int i = vd.size() - 2; i >= 0; --i) printf("%09d", vd[i]); } }
LongInt operator+(const LongInt& other) { LongInt result; int carry = 0; // 进位 int maxChunks = max(vd.size(), other.vd.size()); for (int i = 0; i < maxChunks; ++i) { int chunk1 = (i < vd.size()) ? vd[i] : 0; int chunk2 = (i < other.vd.size()) ? other.vd[i] : 0;
int sum = chunk1 + chunk2 + carry; carry = sum / M; // 每段最多 9 位,进位是 sum / 10^9 result.vd.push_back(sum % M); } // 如果最后还有进位,添加到结果中 if (carry) { result.vd.push_back(carry); } return result; } };
使用示例。
1 2 3 4 5 6 7
intmain(){ LongInt a("1234567853264901234567890"), b("98765432109876543210"); LongInt c = a + b; cout << c.getString() << endl; c.output(); return0; }