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

 

/*
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;
}    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值