首页 > 其他 > 详细

大数加法(STL list)

时间:2016-10-12 00:57:00      阅读:261      评论:0      收藏:0      [点我收藏+]
#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)

原文:http://www.cnblogs.com/KennyRom/p/5951239.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!