//////Digital是每一位上的数,number类是存储大数的链表类(用字符串初始化),insert是从低到高位插入数据的成员函数,nplus是对number类对象进行运算的函数。
#include "stdafx.h"
#include <iostream>
#include <string>
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;
}
以链表形式储存大整数并运算
最新推荐文章于 2022-05-23 20:53:55 发布