체인 테이블 형식으로 대정수를 저장하고 연산하다

6600 단어
//////Digital       ,number          (       ),insert               ,nplus  number          。
#include "stdafx.h"
#include 
#include 
using namespace std;

struct Digital
{
    int x;
    Digital*next;
};

class number
{
    Digital*head;
public:
    number() { head = NULL; }
    number(string&);
    void insert(int);
    void output();
    Digital*Gethead() { return head; }
};

number::number(string& x)
{
    reverse(x.begin(), x.end());
    for (unsigned int i = 0; i < x.length(); i++)
    {
        insert(x[i]-'0');
    }
}

void number::insert(int x)
{
    Digital*d=head;
    if (d==NULL)
    {
        d = new Digital;
        d->next = NULL;
        d->x = x;
        head = d;
    }
    else
    {
        while (d->next != NULL)
        {
            d = d->next;
        }
        d->next = new Digital;
        d->next->next = NULL;
        d->next->x = x;
    }
}

void number::output()
{
    Digital*d = head;
    string s="";
    string t = "";
    while (d->next != NULL)
    {
        t = char(d->x) + '0';
        s.insert(0,t);
        d = d->next;
    } 
    t = char(d->x) + '0';
    s.insert(0, t);
    for (unsigned int i = 0; i < s.length(); i++)
    {
        cout << s[i];
    }
    cout << endl;
}

number nplus(number&a, number&b)
{
    number c;
    Digital*x = a.Gethead();
    Digital*y = b.Gethead();
    int o = 0, p= 0;
    while (x->next!=NULL&&y->next!=NULL)
    {
        int t = x->x + y->x;
        o=t%10;
        c.insert(o+p);
        p = t / 10;
        x = x->next;
        y = y->next;
    }
    int t = x->x + y->x;
    o = t % 10;
    c.insert(o + p);
    p = t / 10;
    if (x->next!=NULL)
    {
        while (x->next != NULL)
        {
            int t = x->x;
            o = t;
            c.insert(o + p);
            p =0;
            x = x->next;
        }
    }
    else
    {
        while (y->next != NULL)
        {
            int t = y->x;
            o = t;
            c.insert(o + p);
            p = 0;
            y = y->next;
        }
    }
    return c;
}

int main()
{
    string s1="1145141919810";
    string s2 = "97";
    number n1(s1);
    number n2(s2);
    n1.output();
    n2.output();
    number n3 = nplus(n1,n2);
    n3.output();
    getchar();
    return 0;
}

좋은 웹페이지 즐겨찾기