- 高精度数
用一个数组去示一个数字。这样这个数字就被称谓是高精度数
基本思路:
1、读入数字保存在字符数组中。
2、字符数组高精度数的位数保存在整型数组的a[0]中。
3、将字符串中的字符逐个转化成数字并保存在整型数组a中。在存储时需要倒序存储。
- a[n++] 是 先n加一
- 高精度整数求幂
#include<iostream>
using namespace std;
class BigInt
{
public:
int n;
int a[10000];
public:
BigInt(int x)
{
n = 0;
while (x > 0)
{
a[n++] = x % 10;
x = x / 10;
}
}
void Output();
void Caculate(int x, int k);
};
void BigInt::Output()
{
for (int i = n - 1; i >= 0; i--)
{
cout << a[i];
}
}
void BigInt::Caculate(int x, int k)
{
for (int i = 0; i < k - 1; i++)
{
int l = 0;
for (int j = 0; j < n; j++)
{
l += a[j] * x;
int t = l;
l = t / 10;
a[j] = t % 10;
}
while (l > 0)
{
a[n++] = l % 10;
l /= 10;
}
}
}
int main()
{
int x, k;
cin >> x >> k;
BigInt b(x);
b.Caculate(x, k);
b.Output();
}
- 高精度整数求和
#include<iostream>
using namespace std;
class BigInt
{
int n;
int a[10000];
public:
BigInt(int x)
{
n = 0;
while (x > 0)
{
a[n++] = x % 10;
x /= 10;
}
}
~BigInt() { }
void Multiply(int x, int k);
void Add(BigInt& b);
void Output();
};
void BigInt::Multiply(int x, int k)
{
for (int i = 0; i < k - 1; i++)
{
int l = 0;
for (int j = 0; j < n; j++)
{
int t = a[j] * x + l;
l = t / 10;
a[j] = t % 10;
}
while (l > 0)
{
a[n++] = l % 10;
l /= 10;
}
}
}
void BigInt::Add(BigInt& b)
{
int l = 0, i;
for (i = 0; i < n && i < b.n; i++)
{
int t = a[i] + b.a[i] + l;
a[i] = t % 10;
l = t / 10;
}
for (; i < n; i++)
{
int t = a[i] + l;
a[i] = t % 10;
l = t / 10;
}
for (; i < b.n; i++)
{
int t = b.a[i] + l;
a[i] = t % 10;
l = t / 10;
}
if (l > 0)
a[i++] = l;
n = i;
}
void BigInt::Output()
{
for (int i = n - 1; i >= 0; i--)
{
cout << a[i];
}
}
int main()
{
int x1, x2, k1, k2;
cin >> x1 >> k1;
BigInt b1(x1);
cin >> x2 >> k2;
BigInt b2(x2);
b1.Multiply(x1, k1);
b2.Multiply(x2, k2);
b1.Add(b2);
b1.Output();
}