对于long long类型也存放不下的超长整数,可以使用字符串模拟的办法来对其进行运算的模拟。此处仅做加法的示范,其他运算思想类似。
每四位视为一个整数,进位等情况对下一次的计算考虑影响。
~~~
#include<iostream>
using namespace std;
#define MAX_LEN 50
int nNumA[MAX_LEN];
int nLenA = 0;
int nNumB[MAX_LEN];
int nLenB = 0;
int nResult[2*MAX_LEN];
int nLenR = 0;
void CharToInt(char *szSource, int *nDes, int *Len)
{
int j = 0;
int nDesLoc = 0;
int nTotalNum = 0;
int thisNum = 0; //当前char的值
int nHead = strlen(szSource) % 4;
if (nHead != 0)
{
for (int k = 0; k< nHead; k++)
{
thisNum = (int)(szSource[k] - '0') + 0;
nTotalNum = nTotalNum*10 + thisNum;
j++;
}
nDes[nDesLoc] = nTotalNum; //数组开头不足四位
nTotalNum = 0;
j = 0;
nDesLoc++;
}
for (int i= nHead; i<strlen(szSource); i++)
{
if (j == 4)
{
nDes[nDesLoc] = nTotalNum; //每一个int数组为上存储四个数字
nTotalNum = 0;
j = 0;
nDesLoc++;
}
thisNum = (int)(szSource[i] - '0') + 0;
nTotalNum = nTotalNum*10 + thisNum;
j++;
}
if (nTotalNum != 0)
{
nDes[nDesLoc] = nTotalNum;
nTotalNum = 0;
j = 0;
nDesLoc++;
}
*Len = nDesLoc;
cout<<"长度为"<<nDesLoc<<endl;
for (int j = 0; j< nDesLoc; j++)
{
cout<<nDes[j]<<" ";
}
cout<<endl;
}
void LenAdd()
{
int ALen = nLenA;
int BLen = nLenB;
int CStart = 0;
int nFlag = 0;
while (ALen != 0 && BLen != 0)
{
nResult[CStart] = (nNumA[ALen-1] + nNumB[BLen-1] + nFlag) % 9999;
nFlag = (nNumA[ALen-1] + nNumB[BLen-1] + nFlag) / 9999;
CStart++;
ALen--;
BLen--;
}
while (ALen > 0)
{
nResult[CStart] = (nNumA[ALen-1] + nFlag) % 9999;
nFlag = (nNumA[ALen-1] + nFlag) / 9999;
CStart++;
ALen--;
}
while (BLen > 0)
{
nResult[CStart] = (nNumB[BLen-1] + nFlag) % 9999;
nFlag = (nNumB[BLen-1] + nFlag) / 9999;
CStart++;
BLen--;
}
nLenR = CStart;
cout<<"相加结果为:"<<endl;
for (int i = CStart-1; i >-1 ; i--)
{
cout<<nResult[i]<<" ";
}
cout<<endl;
}
int main()
{
char szInput[100];
cout<<"输入第一个操作数"<<endl;
cin>>szInput;
CharToInt(szInput, nNumA, &nLenA);
cout<<"输入第二个操作数"<<endl;
cin>>szInput;
CharToInt(szInput,nNumB, &nLenB);
LenAdd();
system("pause");
}
~~~
![](https://box.kancloud.cn/2016-02-18_56c5c49be9e24.jpg)