首页 > 代码库 > 大数加法(STL list)

大数加法(STL list)

#include<iostream>#include<list>#include<string>using namespace std;int main(){	list<int>l1, l2, l3;	string s1, s2;	cin >> s1;	cin >> s2;	//储存大数	for (int i = 0; i<s1.length(); i++)		l1.push_front(s1[i] - ‘0‘);	for (int i = 0; i<s2.length(); i++)		l2.push_front(s2[i] - ‘0‘);	list<int>::iterator it1, it2;	it1 = l1.begin();	it2 = l2.begin();	//进位保存	int carry = 0;	//计算位数相同部分	while (it1 != l1.end() && it2 != l2.end())	{		l3.push_front((*it1 + *it2 + carry) % 10);		carry = (*it1 + *it2 + carry) / 10;		it1++;		it2++;	}	list<int>::iterator it3 = (it1 == l1.end()) ? it2 : it1;	list<int>::iterator it4 = (it1 == l1.end()) ? l2.end() : l1.end();	//计算位数不相同部分	while (it3 != it4)	{		l3.push_front((*it3 + carry) % 10);		carry = (*it3 + carry) / 10;		it3++;	}	l3.push_front(carry);	//输出	for (list<int>::iterator it = l3.begin(); it != l3.end(); it++)		cout << *it;	cout << endl;	return 0;}

  

大数加法(STL list)