总结 : 所有高精度加减乘除,都是按照其运算规律,利用工具人 t 模拟正常运算过程
1. 高精度加法
关键 : 工具人 t ,答案容器 c, 个位放前面, 大数加小数
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e6 + 10;
vector<int> add(vector<int>& a, vector<int>& b)
{
vector<int> c; 答案 c
if(() < ()) return add(b, a);
int t = 0; 工具人 t
for(int i = 0; i < (); i++)
{
t += a[i];
if(i < ()) t += b[i];
c.push_back(t % 10);
t /= 10;
}
if(t) c.push_back(t); 要判断一下 t 是否全放进了 c 里面
return c;
}
int main()
{
string A, B;
vector<int> a, b;
cin >> A >> B;
for(int i = () - 1; i >= 0; i --) a.push_back(A[i] - '0'); 把个位放前面, 方便计算
for(int i = () - 1; i >= 0; i --) b.push_back(B[i] - '0');
auto c = add(a, b); auto 自动判断数据类型
for(int i = () - 1; i >= 0; i--) cout << c[i];
}
2 . 高精度减法
#include<iostream>
#include<vector>
using namespace std;
const int N = 1e6 + 10;
bool cmp(vector<int>& a, vector<int>& b) 注意判断的是 大于等于
{
if(() != ()) return () > ();
for(int i = () - 1; i >= 0; i--)
{
if(a[i] != b[i]) return a[i] > b[i];
}
return true;
}
vector<int> sub(vector<int>& a, vector<int>& b)
{
vector<int> c; 答案 c
int t = 0; 工具人 t
for(int i = 0; i < (); i++)
{
t = a[i] - t;
if(i < ()) t -= b[i];
c.push_back((t + 10) % 10); 保证 push 进去的是正数
if(t < 0) t = 1;
else t = 0;
}
while(() > 1 && () == 0) c.pop_back(); 舍去前导 0
return c;
}
int main()
{
string A, B;
vector<int> a, b;
cin >> A >> B;
for(int i = () - 1; i >= 0; i --) a.push_back(A[i] - '0'); 把个位放前面, 方便计算
for(int i = () - 1; i >= 0; i --) b.push_back(B[i] - '0');、
if(cmp(a,b))
{
auto c = sub(a, b); auto 自动判断数据类型
for(int i = () - 1; i >= 0; i--) cout << c[i];
}
else
{
auto c = sub(b, a);
cout << '-';
for(int i = () - 1; i >= 0; i--) cout << c[i];
}
return 0;
}
3.高精度乘法
#include<iostream>
#include<vector>
using namespace std;
vector<int> mul(vector<int> &A, int b)
{
vector<int> c;
int t = 0;
for(int i = 0; i < () || t; i++) 且 t 不为 0,就一直循环
{
if(i < ()) t += A[i] * b; 每个数都与整个 b 相乘
c.push_back(t % 10);
t /= 10;
}
while(() > 0 && () == 0) c.pop_back(); 去前导 0
return c;
}
int main()
{
string a; a 很长,用字符串表示
int b; b 很短 ,用int 表示
cin >> a >> b;
vector<int> A;
for(int i = () - 1; i >= 0; i--) A.push_back(a[i] - '0');
auto c = mul(A, b);
for(int i = () - 1; i >= 0; i ++) cout << c[i];
return 0;
}
4.高精度除法
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> div(vector<int>& A, int b, int& r)
{
vector<int> c;
r = 0;
for (int i = () - 1; i >= 0; i--)
{
r = r * 10 + A[i];
c.push_back(r / b);
r %= b;
}
reverse((), ());
while (() > 1 && () == 0)c.pop_back();
return c;
}
int main()
{
string a;
int b;
cin >> a >> b;
vector<int> A;
for (int i = () - 1; i >= 0; i--) A.push_back(a[i] - '0');
int r;
auto c = div(A, b, r);
for (int i = () - 1; i >= 0; i--) printf("%d", c[i]);
cout << endl << r << endl;
return 0;
}