@孩子,我无敌了,我才是C++真理
2026-04-17 12:46:37
发布于:江苏
8阅读
0回复
0点赞
不懂不多,也就92行(不加多余换行,提交也正确)。
真理开始



#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
struct BigInt {
std::string digits;
BigInt() = default;
explicit BigInt(const std::string& s) : digits(s) {}
explicit BigInt(long long num) {
if (num == 0) {
digits = "0";
return;
}
bool is_negative = num < 0;
num = std::abs(num);
while (num > 0) {
digits.push_back(num % 10 + '0');
num /= 10;
}
if (is_negative) {
digits.push_back('-');
}
std::reverse(digits.begin(), digits.end());
}
BigInt operator+(const BigInt& other) const {
BigInt result;
int i = digits.size() - 1;
int j = other.digits.size() - 1;
int carry = 0;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0 && digits[i] != '-') {
sum += digits[i] - '0';
i--;
}
if (j >= 0 && other.digits[j] != '-') {
sum += other.digits[j] - '0';
j--;
}
carry = sum / 10;
result.digits.push_back(sum % 10 + '0');
}
std::reverse(result.digits.begin(), result.digits.end());
return result;
}
friend std::ostream& operator<<(std::ostream& os, const BigInt& num) {
os << num.digits;
return os;
}
friend std::istream& operator>>(std::istream& is, BigInt& num) {
is >> num.digits;
if (!isValidInteger(num.digits)) {
is.setstate(std::ios::failbit);
}
return is;
}
private:
static bool isValidInteger(const std::string& s) {
if (s.empty()) return false;
int start = 0;
if (s[0] == '-') {
if (s.size() == 1) return false;
start = 1;
}
for (size_t i = start; i < s.size(); ++i) {
if (!std::isdigit(s[i])) {
return false;
}
}
return true;
}
};
void handleInput(BigInt& a, BigInt& b) {
while (!(std::cin >> a)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
while (!(std::cin >> b)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
void displayResult(const BigInt& a, const BigInt& b, const BigInt& sum) {
std::cout << sum << std::endl;
}
int main() {
BigInt a, b;
handleInput(a, b);
BigInt sum = a + b;
displayResult(a, b, sum);
return 0;
}
这里空空如也

有帮助,赞一个