其他分享
首页 > 其他分享> > 两个大数相加

两个大数相加

作者:互联网

#include <stdio.h>
#include <string.h>
#include "string"

using namespace std;

//把大数的高位/低位翻转
string reverseString(string str)
{
    int iLen = str.length();
    
    if (iLen == 0)
        return str;
    
    for(int i = 0; i< iLen/2; i++)
    {
        char chTemp = str[i];
        str[i] = str[iLen - 1 - i];
        str[iLen - 1 - i] = chTemp;        
    }
    
    return str;
}

string addBigNumber(string str1, string str2)
{
    str1 = reverseString(str1);
    str2 = reverseString(str2);
        
    int iLen1 = str1.length();
    int iLen2 = str2.length();
    
    // make sure that length of str1 >= str2
    string strTemp;
    if(iLen1 < iLen2)
    {
        strTemp = str1;
        str1 = str2;
        str2 = strTemp;
    }
    
    int iLenMax = iLen1 > iLen2 ? iLen1 : iLen2;
    int iLenMin = iLen1 < iLen2 ? iLen1 : iLen2;
    
    char *pRes = (char *) malloc(iLenMax + 2);

    int iCarry = 0;
    int i = 0;
    for(; i < iLenMin; i++)
    {
        int iDigital = ( str1[i] - '0' ) + (str2[i] - '0') + iCarry;
        
        if (iDigital >= 10)
        {
            iCarry = 1;
            iDigital -= 10;            
        }
        else
        {
            iCarry = 0;
        }
        pRes[i] = '0' + iDigital;
        
    }    
    
    for(int j = iLenMin; j  < iLenMax; j++)
    {
        int iDigital = ( str1[j] - '0' )  + iCarry;
        
        if (iDigital >= 10)
        {
            iCarry = 1;
            iDigital -= 10;            
        }
        else
        {
            iCarry = 0;
        }
        pRes[j] = '0' + iDigital;    
    }
    
    if(iCarry == 1)
    {
        pRes[iLenMax] = '0' + 1;
        pRes[iLenMax + 1] = 0;
    }
    else
    {
        pRes[iLenMax] = 0;
    }
    
    string strResult = pRes;
    strResult = reverseString(strResult);
    
    free(pRes);
    return strResult;
}


int main()
{
    string str1 = "12";
    string str2 = "76543";
    string strRes = addBigNumber(str1, str2);
    printf("Hello %s ", strRes.c_str());
    
    return 0;
}

 

标签:两个,string,大数,int,str2,相加,str,str1,pRes
来源: https://www.cnblogs.com/ghnie/p/16669084.html