• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

C++实现两个超大的字符数字相加的算法

OC/C/C++ 水墨上仙 2275次浏览

C++实现两个超大的字符数字相加的算法

#include <iostream>
#include <string>
#include <stack>
using namespace std;
//Acts as an helper function for large numeric string addition
void deleteLeadingZeros(string& num){
	//delete any starting 0's
	if(num[0] == '0'){
		unsigned int strtCpyIndex = 0;
		strtCpyIndex = num.find_first_not_of("0");
		string temp = num.substr(strtCpyIndex);
		num = temp;
	}
}
//adds leading 0's for the smaller string
void equalizeLength(string& num1 , string& num2, char pad = '0'){
	if(num1.size() < num2.size()){
		unsigned int diff = num2.size() - num1.size();
		string temp;
		while(diff--) //add starting zeros
			temp += pad;
		temp += num1;
		num1 = temp;
	}
	else if(num2.size() < num1.size()){
		unsigned int diff = num1.size() - num2.size();
		string temp;
		while(diff--) //add starting zeros
			temp += pad;
		temp += num2;
		num2 = temp;
	}
}
string addLargeNumbers(string num1, string num2)
{	
	//simple error check
	if(num1.empty())
		return num2;
	else if(num2.empty())
		return num1;
	
//check for valid information passed here if you want
	//holds out result of addition
	stack<short> addResult; 
	//addResult in string version
	string returnResult = "";	
	
	//delete any starting 0's	
	//example if num1 = 001
	//after the call below num = 1
	deleteLeadingZeros(num1);
	deleteLeadingZeros(num2);
	//match size by adding in leading 0's for the smaller number
	//example num1 = 100 and num2 = 50
	//after the call num1 = 100 and num2 = 050
	equalizeLength(num1,num2);
	
	int lastAddElem = num1.size()- 1;
	bool hasCarry = false;
	short result = 0; //holds result of each integer addition
	//start calculation
	for(int i = lastAddElem; i >= 0; --i)
	{
		result = (num1[i] - '0') + (num2[i] - '0') ; //convert to decimal and add
		
		if(result < 10 && !hasCarry)
			addResult.push(result);
		else
		{			
			if(hasCarry){
				result += 1; //account for the carry				
				hasCarry = result < 10 ? false : true;
				addResult.push(result%10);
			}
			else
			{
				hasCarry = true;
				addResult.push(result % 10 );
			}
		}
	}
	//check for highest bit carry
	if(hasCarry)
		addResult.push(result/10);
	//extract data
	while(addResult.size()){
		returnResult += (addResult.top() + '0');		
		addResult.pop();
	}
	return returnResult;
}
int main()
{		
	string num1,num2;
	while(true){
		cout<<"Enter 2 integer for addition : ";
		cin >> num1 >> num2;
		cout <<num1 << "+" << num2 <<" = "<<addLargeNumbers(num1,num2)<<endl;
	}
	
}


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明C++实现两个超大的字符数字相加的算法
喜欢 (0)
加载中……