Big vs Big(链表)

【题目描述】

Calculate the addtion of any two positive big integers.
Requirements:
Test data can be more than 64 digits, therefore you MUST use  a linked list to store an integer (any big).

【输入】

The first line contains the number of test cases,  N.
 In the next 2*N lines, each line contains a string of number. 

【输出】

Out put N lines. Each line represent the sum of A and B. 

【我的程序】

#include <stdlib.h>
#include <iostream>
using namespace std;

typedef struct node{ int num;  node *av; }* wei;

wei newWei(int x)
{
    wei y=(wei)malloc(sizeof(node));
    y->num=x; y->av=NULL;
    return y;
}

int main()
{
    int n;
    char ch;

    cin>> n; cin.get();
    for (int i=0;i<n;i++)
    {
        wei x=newWei(cin.get()-'0');
        while ((ch=cin.get())!='\n'){ wei p=newWei(ch-'0'); p->av=x; x=p; }

        wei y=newWei(cin.get()-'0');
        while ((ch=cin.get())!='\n'){ wei p=newWei(ch-'0'); p->av=y; y=p; }

        wei re=newWei(x->num+y->num);
        int jw=(re->num)/10; re->num%=10;
        x=x->av; y=y->av;

        while (x!=NULL && y!=NULL)
        {
            wei p=newWei(x->num+y->num+jw); jw=(p->num)/10; p->num%=10;
            p->av=re; re=p;
            x=x->av; y=y->av;
        }

        while (y!=NULL)
        {
            wei p=newWei(y->num+jw); jw=p->num/10; p->num%=10;
            p->av=re; re=p;
            y=y->av;
        }

        while (x!=NULL)
        {
            wei p=newWei(x->num+jw); jw=p->num/10; p->num%=10;
            p->av=re; re=p;
            x=x->av;
        }

        if (jw>0) cout<< jw;
        while (re!=NULL){ cout<< re->num; re=re->av; }
        cout<< endl;
    }
    return 0;
}


发布了44 篇原创文章 · 获赞 9 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章