c ++语言大整数加法
时间: 2023-09-10 20:07:39 浏览: 69
大整数加法可以使用字符串来表示,然后按照从低位到高位的顺序逐位相加,注意进位即可。
以下是一个使用C++实现的例子:
```c++
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string add(string num1, string num2) {
reverse(num1.begin(), num1.end()); // 反转字符串
reverse(num2.begin(), num2.end());
int len1 = num1.size(), len2 = num2.size();
int len = max(len1, len2);
int carry = 0;
string result;
for (int i = 0; i < len; i++) {
int x = i < len1 ? num1[i] - '0' : 0; // 如果长度不够,则设为0
int y = i < len2 ? num2[i] - '0' : 0;
int sum = x + y + carry;
carry = sum / 10;
result += to_string(sum % 10);
}
if (carry) result += "1"; // 如果最高位有进位,则加上1
reverse(result.begin(), result.end());
return result;
}
int main() {
string num1 = "123456789";
string num2 = "987654321";
cout << add(num1, num2) << endl; // 输出 1111111110
return 0;
}
```
在这个例子中,我们使用了字符串反转的技巧来让逐位相加更加方便,最后再反转回来得到最终结果。同时,我们使用了 `to_string` 函数将数字转化为字符串,方便与结果字符串相加。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)