大数相加的算法

有次周五失眠,尝试下了下大数相加的算法。这个周末再优化下,先露露脸。

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>

using namespace std;

char num1[] =  “+1030000000000910”;
char num2[] =      “+10”;
int strlen1 = strlen (num1);
int strlen2 = strlen (num2);
int key = 0;
char cNum[20] = {0};

void NumAdd()
{
    int i = strlen1 – 1;
    int j = strlen2 – 1;

    while (i >= 1 && j >= 1)
    {
        if ((cNum[19 – ((strlen1 – 1) – i)] = (num1[i] + num2[j] – ‘0’ + key)) >= ‘9’ + 1 )
        {
            key = 1;
           cNum[19 – (strlen1 – 1 – i)] -= 10;
        }
        else
        {
            key = 0;
        }
        i–;
        j–;
    }

    while(i >= 1)
    {
        if (key == 1)
        {
            if ((cNum[19 – (strlen1 – 1 – i)] = num1[i] + 1 ) > ‘9’)
            {
                cNum[19 – ((strlen1 – 1) – i)]  =  cNum[19 – ((strlen1 – 1) – i)] – 10 ;
                key = 1;
            }
            else
            {
                key = 0;
            }
        }
        else
            cNum[19 – (strlen1 – 1 – i)] = num1[i];

        i–;
    }

    while(j >= 1)
    {
        if (key == 1)
        {
            if ((cNum[19 – (strlen2 – 1 – j)] = num2[j] + 1) > ‘9’)
            {
                cNum[19 – (strlen2 – 1 – j)]  =  cNum[19 – (strlen2 – 1 – j)] – 10 ;
                key = 1;
            }
            else
            {
                key = 0;
            }
        }
        else
            cNum[19 – ((strlen2 – 1) – j)] = num2[j];
        j–;
    }

    if (key == 1)
        if (strlen1 > strlen2)
            cNum[19 – ((strlen1 – 1) – i)] = 1 + ‘0’;
        else
            cNum[19 – ((strlen2 – 1) – j)] = 1 + ‘0’;
    else
        key = 0;

    cNum[0] = num1[0];

    return;
}

void NumDel()
{
    return;
}

int main (int argc, char *argv[])
{
    int iSign1;
    int iSign2;

    if (num1[0] > ‘0’ && num1[0] < ‘9’)
        iSign1 = ‘+’;
    else
        iSign1 = num1[0];

    if (num2[0] > ‘0’ && num2[0] < ‘9’)
        iSign2 = ‘+’;
    else
        iSign2 = num2[0];

    if (iSign1 == iSign2)
    {
        NumAdd();

        for (int t = 0; t < 20; t++)
        {
            cout<<cNum[t];
        }
        cout<<endl;
    }
    else
    {
        NumDel();
    }
 }

点赞