【C++】已经通过
#include<string>
#include<algorithm>
using namespace std;
//小于返回true;大于或者等于返回false
bool isless(string a, string b) {
if (a.size() > b.size()) {
return false;
}
else if (a.size() == b.size()) {
for (int i = 0; i < a.size(); i++) {
if (a[i] != b[i]) {
return a[i] < b[i];
}
}
return false;
}
else {
return true;
}
}
string stradd(string a, string b) {
string ls, ss;
if (a.size() > b.size()) {
ls = a; ss = b;
}
else {
ls = b; ss = a;
}
if (ls.size() == 0)return "0";
if (ss.size() == 0)ss = "0";
reverse(ls.begin(), ls.end());
reverse(ss.begin(), ss.end());
int carry = 0; int i = 0;
for (; i< ss.size(); i++) {
if (ls[i] - '0' + ss[i] - '0' + carry <= 9) {
ls[i] = (ls[i] - '0' + ss[i] - '0' + carry) + '0';
carry = 0;
}
else {
ls[i] = (ls[i] - '0' + ss[i] - '0' + carry - 10) + '0';
carry = 1;
}
}
if (i == ls.size()&&carry==1) {
ls += "1";
}
else {
while (carry == 1) {
if (ls[i] - '0' + + carry <= 9) {
ls[i] = (ls[i] - '0' + carry) + '0';
carry = 0;
}
else {
ls[i] = (ls[i] - '0' + carry - 10) + '0';
carry = 1;
if (i == ls.size() - 1) {
ls += "1";
carry = 0;
}
}
i++;
}
}
reverse(ls.begin(), ls.end());
return ls;
}
//返回a-b,只考虑a>=b的情况
string strsub(string a, string b) {
bool positive = true;//true表示正数,false表示结果为负
string ls, ss;
if (isless(a, b)) {
positive = false;
ls = b; ss = a;
}
else {
positive = true;
ls = a; ss = b;
}
if (ls.size() == 0)return "0";
if (ss.size() == 0)ss = "0";
reverse(ls.begin(), ls.end());
reverse(ss.begin(), ss.end());
int carry = 0; int i = 0;
for (; i < ss.size(); i++) {
if (ls[i] - ss[i] - carry < 0) {
ls[i] = ls[i] - ss[i] - carry + 10 + '0';
carry = 1;
}
else {
ls[i] = ls[i] - ss[i] - carry + '0';
carry = 0;
}
}
for (; i < ls.size(); i++) {
if (ls[i] - '0'-carry < 0) {
ls[i] = ls[i] - carry + 10 ;
carry = 1;
}
else {
ls[i] = ls[i] - carry ;
carry = 0;
}
}
reverse(ls.begin(), ls.end());
while (ls[0] == '0') {
//cout << "清除零" << endl;
ls.erase(0, 1);
}
if (ls == "") {
ls = "0";
}
if (positive) {
}
else {
ls.insert(0, "-");
}
return ls;
}
string strmul(string a, string b) {
string ls, ss;
if (a.size() > b.size()) {
ls = a; ss = b;
}
else {
ls = b; ss = a;
}
if (ss.size() == 0)return "0";
string result = "";
for (int i = 0; i < ss.size(); i++) {
string temp = "";
for (int j = 0; j < ss[i]-'0'; j++) {
temp = stradd(temp, ls);
}
result = stradd(result, temp);
if (i != ss.size() - 1) {
result += "0";
}
}
/*reverse(ls.begin(), ls.end());
reverse(ss.begin(), ss.end());*/
return result;
}
void test() {
string s1 = "16";
string s2 = "4";
cout << strsub(s1, s2) << endl;
cout << "-----------------------" << endl;
}
int main() {
//test();
string a, b;
cin >> a >> b;
cout << stradd(a, b) << endl << strsub(a, b) << endl << strmul(a, b) << endl;
return 0;
}