大数加法(C++String版本,含负数)

这篇博客介绍了如何使用C++处理大整数加法的问题,包括正数、负数的情况。通过给出的示例输入和输出,展示了程序的运行效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给出2个大整数A,B,计算A+B的结果。

Input

第1行:大数A 
第2行:大数B 
(A,B的长度 <= 10000 需注意:A B有可能为负数)

Output

输出A + B

Sample Input

68932147586
468711654886

Sample Output

537643802472

C++版本的,我分了三种情况1:全正,2:全负,3:一正一负,看起来稍微有点长:

#include<iostream>
#include<vector>
#include<algorithm> 
#include<string>
using namespace std;
string Plus(string a,string b){
	string temp="",ans="";  //temp是可能带前缀0的半成品 ,ans是返回结果 
	int *A,*B;     //数字数组 
	if(a[0]!='-'&&b[0]!='-'){
		if(a.length()<b.length()){
			swap(a,b);
		} 
		int n=a.length();
		int m=b.length(); 
		A=new int[n+1];
		A[0]=0;
		for(int i=0;i<n;i++){
			A[i+1]=a[i]-'0';
		}
		B=new int[n+1];
	    int t=n-m+1;
		for(int i=0;i<t;i++){
			B[i]=0;
		} 
		for(int i=t;i<=n;i++){
			B[i]=b[i-t]-'0';
		}		
		for(int i=n;i>=0;i--){
			A[i]+=B[i];
			if(A[i]>9){
				A[i]-=10;
高精度字符串加法C++中通常通过动态数组或者`std::vector`存储大整数,并实现自定义的加法操作。对于考虑负数的情况,我们需要处理正数加负数、两个负数以及不同位数的相加。以下是一个简单的模板,使用了`std::vector`来存储字符数组代表的大数: ```cpp #include <iostream> #include <vector> #include <algorithm> // 定义大数结构体 struct BigInt { std::vector<char> digits; bool isNegative; // 构造函数、获取长度等基础操作... }; // 自定义加法函数 BigInt add(BigInt a, BigInt b) { if (a.isNegative != b.isNegative) { // 判断是否一正一负 BigInt result = a.isNegative ? -b : a; // 取绝对值 return add(result, b); } BigInt result; result.isNegative = a.isNegative; // 结果的负号取决于原始数值 size_t maxLen = std::max(a.digits.size(), b.digits.size()); result.digits.resize(maxLen + 1); // 预留足够的空间 // 数字从右向左逐位相加 for (size_t i = maxLen; i > 0; --i) { char sum = '0' + (a.digits[i - 1] - '0' + b.digits[i - 1] - '0') % 10; // 相加并考虑进位 result.digits[i] = static_cast<char>(sum); if (result.digits[i - 1] >= '9' && sum != '0') { // 检查是否需要进位 result.digits[i - 1]++; if (i == maxLen) { // 如果是最高位还需要进位,则处理最高位 if (result.digits[0] != '0' || a.isNegative) { result.digits[0] = '1'; result.isNegative = true; // 进位导致最高位变正 } else { result.isNegative = false; } } } } return result; } // 示例 int main() { BigInt num1 = {"12345", true}; // 负数12345 BigInt num2 = {"67890", false}; // 正数67890 BigInt sum = add(num1, num2); // 输出结果 // ... return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值