高精度加法的用途在于将原本long long int类型不支持的多位数运算通过字符串的方式变为可能。高精度加法是高精度算法中较为简单与常用的算法,实现的方式也较多,例如分段相加,或像小学竖式运算那样每一位都进行相加,逢十进一,或是使用神奇的hugeint(没用过,也许好用)。
主要考验代码实现能力与细节处理,难度大约为普及组水平,没有太高的思维难度。
以下代码为300位自然数范围内的加法运算:
//c++ High precision Addition
//#pragma GCC optimize(3, "Ofast", "inline")
#include <bits/stdc++.h>
using namespace std;
const long long int High_Precision_Size = 300;
const int _null = 0;
int Result[High_Precision_Size];
class High_Precision
{
private:
int Answer[High_Precision_Size];
public:
virtual inline int Addition(char NumArr_A[], char NumArr_B[]) {
int NumSize_A = strlen(NumArr_A);
int NumSize_B = strlen(NumArr_B);
int Num_A[High_Precision_Size];
int Num_B[High_Precision_Size];
memset(Num_A , _null, sizeof(Num_A) );
memset(Num_B , _null, sizeof(Num_B) );
memset(Answer, _null, sizeof(Answer));
for(int i = 0; i < NumSize_A; i++)
Num_A[i] = NumArr_A[NumSize_A - i - 1] - '0';
for(int i = 0; i < NumSize_B; i++)
Num_B[i] = NumArr_B[NumSize_B - i - 1] - '0';
int Maxlen = max(NumSize_A, NumSize_B) + 2;
for(int i = 0; i < Maxlen; i++) {
Answer[i] += Num_A[i] + Num_B[i];
if(Answer[i] >= 10) {
Answer[i+1] += Answer[i] / 10;
Answer[i] %= 10;
}
}
int ZeroLock = 0;
int node = 0;
for(int i = Maxlen; i >= 0; i--) {
if(Answer[i] != 0) {
ZeroLock = i;
break;
}
}
for(int i = ZeroLock; i >= 0; i--)
Result[node++] = Answer[i];
for(int i = 0; i < node >> 1; i++)
swap(Result[i], Result[node/2 - i - 1]);
return node;
}
}High_Precision;
inline void work(void);
int main(void) {
ios::sync_with_stdio(false);
std::cin.tie(0);
//freopen(".in", "r", stdin);
//freopen(".out", "w", stdout);
work();
return 0;
}
inline void work(void) {
char Num_A[High_Precision_Size];
char Num_B[High_Precision_Size];
memset(Result, _null, sizeof(Result));
//printf("Please input two numbers.\n");
cin >> Num_A;
cin >> Num_B;
int Maxlen = High_Precision.Addition(Num_A, Num_B);
for(int i = 0; i < Maxlen; i++)
wcout << Result[i];
}
|