使用数组的来表示一个较大的数:
#include<iostream>
using namespace std;
void add(int* &a, int length) {
int c = 1;
//c代表进位,完成对数组的更新,并保留最高为的进位;
for (int i = length - 1;i >= 0;i--) {
if ((a[i] += c) == 10) {
c = 1;
a[i] = 0;
}
else {
c = 0;
}
}
if (c == 1) {//最高位发生进位;
int*oldElem = a;//保留旧的数组地址;
a = new int[++length];
//将就数组数据迁至新数组;
for (int i = 0, k = 1;k<length;k++)
a[k] = oldElem[i++];
a[0] = 1;//最高位赋值为1;
delete[]oldElem;
}
for (int i = 0;i<length;i++)//数据的输出;
cout << a[i] << " ";
}
int main()
{
int n;
cin>>n;
int* a = new int[n];
for (int i = 0;i<n;i++)
cin >> a[i];
add(a, n);
delete[]a;
}