一.加法
ac代码:
#include <bits/stdc++.h>
using namespace std;
vector<int> x,y,z;
string a, b;
int main()
{
cin >> a >> b;
for (int i = a.size() - 1; i >= 0; i--) x.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--) y.push_back(b[i] - '0');
int t = 0;
for (int i = 0; i < x.size() || i < y.size(); i++) {
if (i < x.size()) t += x[i];
if (i < y.size()) t += y[i];
z.push_back(t % 10);
t /= 10;
}
if(t) z.push_back(t);//加完之后数位多了的情况
for (int i = z.size() - 1; i >= 0; i--) {
if (i != z.size()) cout << z[i];
else cout << z[i] << endl;
}
return 0;
}
二.减法
ac代码:
#include <bits/stdc++.h>
using namespace std;
vector<int> x,y,z;
string a, b;
bool pd()//判断x,y两个数据大小
{
if (x.size() != y.size()) return x.size() > y.size();
for (int i = x.size() - 1; i >= 0; i--) {
if (x[i] != y[i]) return x[i] > y[i];
}
return 1;
}
int main()
{
cin >> a >> b;
for (int i = a.size() - 1; i >= 0; i--) x.push_back(a[i] - '0');
for (int i = b.size() - 1; i >= 0; i--) y.push_back(b[i] - '0');
int t = 0;
int tmp = 0;
if (pd()) {
for (int i = 0; i < x.size(); i++) {
t = x[i] - t;
if (i < y.size()) t -= y[i];
z.push_back((t + 10) % 10);
if (t < 0) t = 1;
else t = 0;
}
}
else {
tmp = 1;//标记负号
for (int i = 0; i < y.size(); i++) {
t = y[i] - t;
if (i < x.size()) t -= x[i];
z.push_back((t + 10) % 10);
if (t < 0) t = 1;
else t = 0;
}
}
while (z.size() > 1 && z.back() == 0) z.pop_back();//减法出现0,去除多余的0
if (tmp) cout << "-";
for (int i = z.size() - 1; i >= 0; i--) {
if (i != z.size()) cout << z[i];
else cout << z[i] << endl;
}
return 0;
}
三.乘法
ac代码:
#include <bits/stdc++.h>
using namespace std;
vector<int> x, y, z;
string a, b;
int c;
int main()
{
cin >> a >> c;
for (int i = a.size() - 1; i >= 0; i--) x.push_back(a[i] - '0');
int t = 0;
for (int i = 0; i < x.size(); i++) {
t += x[i] * c;
z.push_back(t % 10);
t /= 10;
}
while (t) {
z.push_back(t % 10);
t /= 10;
}
while (z.size() > 1 && z.back() == 0) z.pop_back();//乘0的情况
for (int i = z.size() - 1; i >= 0; i--) {
if (i != z.size()) cout << z[i];
else cout << z[i] << endl;
}
return 0;
}
四.除法
ac代码:
//如果只有除法最好使用正序插入,但由于进行四则运算要与其它运算保持一致所以这里使用逆序
#include <bits/stdc++.h>
using namespace std;
vector<int> x, y, z;
string a, b;
int c;
int main()
{
cin >> a >> c;
for (int i = a.size() - 1; i >= 0; i--) x.push_back(a[i] - '0');
int t = 0;
for (int i = x.size() - 1; i >= 0; i--) {
t = t * 10 + x[i];
z.push_back(t / c);
t %= c;
}
reverse(z.begin(), z.end());
while (z.size() > 1 && z.back() == 0) z.pop_back();
for (int i = z.size() - 1; i >= 0; i--) {
if (i != 0) cout << z[i];
else cout << z[i] << endl;
}
cout << t << endl;//t作余数
return 0;
}