zoukankan      html  css  js  c++  java
  • 大数加法(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;
    }
    

      

  • 相关阅读:
    redis概要学习
    http协议格式详解
    浅谈mysql
    linux常用命令
    Linux 程序管理
    认识与分析日志文件
    认识与学习bash
    例行任务管理
    软件安装的三大方法
    关于一些感慨
  • 原文地址:https://www.cnblogs.com/KennyRom/p/5951239.html
Copyright © 2011-2022 走看看