Voltaris @ 2024-07-18 10:03:28
50分108行求改
#include<bits/stdc++.h>
using namespace std;
class Bigint;
istream& operator>>(istream& is, Bigint& bigint);
ostream& operator<<(ostream& os, const Bigint& bigint);
class Bigint {
private:
string value;
public:
Bigint(const string& str) : value(str) {}
friend istream& operator>>(istream& is, Bigint& bigint);
friend ostream& operator<<(ostream& os, const Bigint& bigint);
Bigint operator+(const Bigint& other) const {
string result;
string str1 = value;
string str2 = other.value;
int len1 = str1.length();
int len2 = str2.length();
int carry = 0;
if (len1 > len2) {
str2 = std::string(len1 - len2, '0') + str2;
} else {
str1 = std::string(len2 - len1, '0') + str1;
}
for (int i = str1.length() - 1; i >= 0; i--) {
int sum = (str1[i] - '0') + (str2[i] - '0') + carry;
result.insert(result.begin(), (sum % 10) + '0');
carry = sum / 10;
}
if (carry > 0) {
result.insert(result.begin(), carry + '0');
}
return Bigint(result);
}
Bigint operator-(const Bigint& other) const {
string result;
string str1 = value;
string str2 = other.value;
int len1 = str1.length();
int len2 = str2.length();
int borrow = 0;
if (len1 > len2) {
str2 = string(len1 - len2, '0') + str2;
} else {
str1 = string(len2 - len1, '0') + str1;
}
for (int i = str1.length() - 1; i >= 0; i--) {
int diff = (str1[i] - '0') - (str2[i] - '0') - borrow;
if (diff < 0) {
diff += 10;
borrow = 1;
} else {
borrow = 0;
}
result.insert(result.begin(), diff + '0');
}
result.erase(0, std::min(result.find_first_not_of('0'), result.size() - 1));
return Bigint(result);
}
};
std::istream& operator>>(std::istream& is, Bigint& bigint) {
std::string input;
is >> input;
bigint.value = input;
return is;
}
std::ostream& operator<<(std::ostream& os, const Bigint& bigint) {
os << bigint.value;
return os;
}
string STRING_INPUT(){
string inputs;
string warn="Please don't enter characters other than numbers.";
cin>>inputs;
for(int i=0;i<inputs.length();i++){
if(!(inputs[i]>='0'&&inputs[i]<='9')) {
cout<<warn;
return "";
}
}
return inputs;
}
int main(){
Bigint a=STRING_INPUT();
Bigint b=STRING_INPUT();
cout<<a+b;
return 0;
}
by Enoch2013 @ 2024-07-18 10:09:52
@Yaofangyu 这道题不是高精度,ac code:
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
cout << a+b << endl;
return 0;
}
求关注,qwq
by liuli688 @ 2024-07-18 10:14:34
@Yaofangyu 负数?
by SuperRobot @ 2024-07-18 10:17:22
凡尔赛之神
by Voltaris @ 2024-07-18 10:20:41
@liuli688 负数怎么写?我不是很会QwQ
by Voltaris @ 2024-07-18 10:25:54
@SuperRobot 真的50分
by liuli688 @ 2024-07-18 10:33:09
@Yaofangyu 给 Bigint
类加一个成员,记录正负性
将构造函数改一下,如果输入是负数就把字符串处理后存进 value
里,同时更改正负性
加减法分类讨论,以加法为例: | |||
---|---|---|---|
减法同理,稍微处理就行了。
by Voltaris @ 2024-07-18 10:39:46
@liuli688 感谢大佬
by SuperRobot @ 2024-07-24 08:57:21
@Yaofangyu 我是蒟蒻 :P