c++ 大数相加

想实现大数相加必须要用数组或者字符串实现,以前遇到大数相加用到过好多次数组,所以这次打算用字符串做一下,但换汤不换药,开干!

下面是我的思路代码,调用了若干API,效率可能不高,但容易理解。

#include
#include
using namespace std;
string res="";
void BigNumAdd(string str1,string str2,int gap);
int main(){
	string a,b;
	int n;
	int lena,lenb;
	int start,gap;
	cout << "您想测试几组数据?" << endl;
	scanf("%d",&n);
	for(int i = 0;i < n;i ++){
		res = "";
		cout << "请输入第" << i+ 1<< "组数据,两个数以空格分开" << endl;
		cin >> a >> b;
		lena = a.length();
		lenb = b.length();
	    if(lena < lenb) BigNumAdd(a,b,lenb - lena);
	    else BigNumAdd(b,a,lena - lenb);

	}
	
	return 0;
}

void BigNumAdd(string str1,string str2,int gap){
	int i,j;
	int flag=0;
	char num;
	for(i = str1.length() - 1;i >= 0;i --){
		if(flag == 1) num = 1;
		else num = 0;
		if(str1[i] + str2[i+gap] + num >= 106) flag = 1;
		else flag = 0;
		num = num + str1[i] + str2[i+gap] - 48 - (flag == 1 ? 10 : 0);
		res.append(1,num);
	}	
	reverse(res.begin(),res.end());
	string oth(str2,0,gap);
	if(flag == 0){
		res = oth + res;
	}
	else{
		for(i = oth.length() - 1;i >= 0;i --){
			if(flag + oth[i] > '9') flag = 1;
			else flag = 0;
			oth[i] = oth[i] + flag - (flag == 1 ? 10 : 0);
		}
		if(flag == 1){
			oth = "1" + oth;
		}
		res = oth + res;
	}
    cout << "相加结果是:" << res << endl << endl;;
}

你可能感兴趣的:(杂项)