c++大整数从末尾开始相加
时间: 2023-07-27 17:07:21 浏览: 51
实现大整数从末尾开始相加的方法如下:
1. 将两个大整数按位存储到两个数组中,从末位开始存储。
2. 从末位开始遍历两个数组,将对应位上的数字相加并加上进位值,得到当前位的结果。
3. 如果当前位的结果大于等于10,则需要产生进位,将进位值加到下一位的计算中。
4. 将当前位的结果存储到结果数组中。
5. 当两个数组都遍历完毕时,如果最高位有进位,则需要将进位值加到结果数组的下一位。
以下是一段 C++ 代码实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<int> add(vector<int>& a, vector<int>& b) {
vector<int> res(max(a.size(), b.size()));
int carry = 0;
int i = a.size() - 1, j = b.size() - 1, k = res.size() - 1;
while (i >= 0 || j >= 0 || carry > 0) {
int sum = carry;
if (i >= 0) sum += a[i--];
if (j >= 0) sum += b[j--];
res[k--] = sum % 10;
carry = sum / 10;
}
return res;
}
int main() {
vector<int> a = {9, 9, 9, 9};
vector<int> b = {1};
vector<int> res = add(a, b);
for (int i = 0; i < res.size(); i++) {
cout << res[i];
}
cout << endl; // 输出 10000
return 0;
}
```