您的位置:首页 > 其它

大数整数相加(忽略负数)

2011-07-11 17:48 323 查看
/*
Name:
Copyright:
Author:
Date: 10/07/11 21:33
Description:
define the carry symbol of each byte is iCarry
define the sum symbol of each byte is iSum
利用整数序列前后多于的0换来了代码的可读性。
注意0+0没有处理。因为0+0 =0 打印结果事后会忽略多余的0
*/
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<string>
using namespace std;
//get user input. we use the string type. init the lenth 1000 with '0'
string GetUserInPut(string szInPutPrompt)
{
string szInPut (1000,'0');
cout<<szInPutPrompt<<endl;
cin>>szInPut;
szInPut.append(1000-szInPut.size(),'0'); //必须的,string重载了>>会重新生成字符串复制。长度会变化的,不是以前的。应且NULL结束
return szInPut;
}
//calculate the sum bwteen the summand and the addend. calculate the summmand adn addend with the reversed sequence
string CalculateSum(string szSummandStr,string szAddendStr)
{
string szSumStr(10010,'0');
int iIndexAddend = szAddendStr.size()-1;
int iIndexSummand = szSummandStr.size() -1;
int iCarray = 0;
int iSum = 0;
int iIndexSum = 0;
for(iIndexSum = 0; iIndexAddend >= 0;iIndexAddend--,iIndexSummand--, iIndexSum++)
{
iSum = ((szSummandStr.at(iIndexSummand) - '0') + (szAddendStr.at(iIndexAddend) - '0') + iCarray) % 10; // sum
iCarray = ((szSummandStr.at(iIndexSummand) - '0') + (szAddendStr.at(iIndexAddend) - '0')) / 10; // carry
szSumStr.at(iIndexSum) = iSum + '0'; //sum
}
szSumStr.at(iIndexSum) = szSumStr.at(iIndexSum) + iCarray; // add the last carry
return szSumStr;
}
void PrintIngoreCharacter(string szPrintStr ,char ch)
{
int iIndexEnd = 0;
int iIndexStart =0;
//ignore the 0 front,find the lowest byte
for(iIndexStart = 0;iIndexStart<szPrintStr.size();iIndexStart++)
{
if(szPrintStr.at(iIndexStart)!=ch)
break;
}
//ignore the 0 back ,find the highest byte.
for(iIndexEnd = szPrintStr.size() -1 ; iIndexEnd >= 0 ; iIndexEnd--)
{
if(szPrintStr.at(iIndexEnd)!=ch)
{
break;
}
}
for(int iIndex=iIndexEnd;iIndex >= iIndexStart; iIndex--)
{
cout<<szPrintStr.at(iIndex);
}
cout<<endl;
system("pause");
}
int main()
{
string szSummandStr = GetUserInPut("inPut Summand please");
string szAddendStr = GetUserInPut("inPut Addend Please");
string szSumStr = CalculateSum(szSummandStr,szAddendStr);
PrintIngoreCharacter(szSumStr,'0');
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: