大数相加的算法

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

#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();
    }
 }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值