高精度加法
步骤
1.将两个加数以字符串形式输入
2.分别将两数倒序存入数组中
3.对应位分别相加
4.处理进位
5.输出结果
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
string x, y;
int la, lb, lc;
int a[N], b[N], c[N];
void add(int c[],int a[],int b[])
{
for (int i = 0; i < lc;i++)
{
c[i] += a[i] + b[i];
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
if(c[lc])
lc++;
for (int i = lc-1; i >=0;i--)
{
cout << c[i];
}
cout << endl;
}
int main()
{
cin >> x >> y;
la = x.size(), lb = y.size();
lc = max(la, lb);
for (int i = 0; i < la;i++)
a[i] = x[la - i - 1] - '0';
for (int i = 0; i < lb;i++)
b[i] = y[lb - i - 1] - '0';
add(c, a, b);
return 0;
}
高精度减法
步骤
- 将被减数与减数以字符串形式输出
- 判断两数长度 计算原理为用长的数减短的数
- 分别将两数倒序存放在数组中
- 逐位相减 处理借位
- 处理前导零
- 输出结果
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
string x, y;
int la, lb, lc;
int a[N], b[N], c[N];
bool cmp(string& x,string& y)
{
if(x.size() != y.size())
return x.size() < y.size();
return x < y;
}
void sub(int c[],int a[],int b[])
{
for (int i = 0; i < lc;i++)
{
c[i] += a[i] - b[i];
if(c[i] < 0)
{
c[i] += 10;
c[i + 1] -= 1;
}
}
while(lc > 1 && c[lc-1] == 0)
{
lc--;
}
for (int i = lc - 1; i >= 0;i--)
{
cout << c[i];
}
cout << endl;
}
int main()
{
cin >> x >> y;
if(cmp(x,y))
{
cout << '-';
swap(x, y);
}
la = x.size(), lb = y.size(), lc = max(la, lb);
for (int i = 0; i < la;i++)
a[i] = x[la - i - 1] - '0';
for (int i = 0; i < lb;i++)
b[i] = y[lb - i - 1] - '0';
sub(c, a, b);
return 0;
}
高精度乘法
步骤
- 将两个乘数分别以字符串的形式输入
- 分别倒序存储在数组中
- 逐位计算乘法(参考小学乘法竖式)
- 处理进位、前导零
- 输出结果
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
string x, y;
int la, lb, lc;
int a[N], b[N], c[N];
void mul(int c[],int a[],int b[])
{
for (int i = 0; i < la;i++)
{
for (int j = 0; j < lb;j++)
{
c[i + j] += a[i] * b[j];
}
}
//处理进位
for (int i = 0; i < lc;i++)
{
c[i + 1] += c[i] / 10;
c[i] %= 10;
}
while(lc > 1 && c[lc-1] == 0)
{
lc--;
}
for (int i = lc - 1; i >= 0;i--)
{
cout << c[i];
}
cout << endl;
}
int main()
{
cin >> x >> y;
la = x.size(), lb = y.size(), lc = la + lb;
for (int i = 0; i < la;i++)
a[i] = x[la - i - 1] - '0';
for (int i = 0; i < lb;i++)
b[i] = y[lb - i - 1] - '0';
mul(c, a, b);
return 0;
}
高精度乘法
步骤
- 将被除数(高精度)以字符串形式输入,除数以整型输入
- 将被除数倒序存入数组中
- 从高位到低位逐位计算(借鉴小学除法竖式:计算当前位的被除数 并记录本次余数)
- 处理前导零
- 输出结果
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
string x;
int b;
int a[N], c[N];
int la, lc;
void sub(int c[],int a[], int b)
{
long long t = 0;
for (int i = la - 1; i >= 0;i--)
{
t = t * 10 + a[i];
c[i] = t / b;
t %= b;
}
while(lc > 1 && c[lc-1] == 0)
lc--;
for (int i = lc - 1; i >= 0;i--)
cout << c[i];
cout << endl;
}
int main()
{
cin >> x >> b;
la = lc = x.size();
for (int i = 0; i < la;i++)
{
a[i] = x[la - i - 1] - '0';
}
sub(c, a, b);
return 0;
}

被折叠的 条评论
为什么被折叠?



