Algorithm description
1、The component of the algorithm is little, simple simulation accounts for the most.
2、Addition and subtraction are base operations,
Multiplication bases on the addition and exponentiation bases on the Multiplication.
3、All the operation begins from the lowest order so in the linked list the digit with an order n points to the digit with the order n+1, for example one:
num:1234
linked list:
4、When outputting a list, the digit with a higher order should come first than that with a lower order, but in the list , access to a digit with an order n is impossible unless the digit with the order n-1 is known. To overcome this problem, there must be a function to reverse the list, continue for the example one:linked list after reversing:
5、For the exponentiation operation, there is an algorithm:
exp(a,n)= a*exp(a,n-1), when n is even(exp(a*a,n/2), when n is odd.)
Analysis and discussion
There are many bugs in fact.
When the number is negative, function will delete the sign ‘-‘, which is inevitable to change the origin number, making it to be positive. So, a number should only be used once. For example, exp(-1,3)=mul(-1,exp(-1,2)), exp(-1,2) will be called prior to mul(), -1 become 1 after exp(-1,2), so mul(-1,exp(-1,2)) become mul(1,exp(-1,2)), that is the problem.
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cassert>
#include<ctime>
#define MAXN 10000000
using namespace std;
int arr1[MAXN+5];
int arr2[MAXN+5];
struct Node{
int value;
Node *adj;
Node(int v,Node *n){
value=v;
adj=n;
}
};
Node *Add(Node *,Node *);
Node *Sub(Node *,Node *);
Node *Reverse(Node *L){
Node *head,*tail,*p;
p=new Node(L->value,NULL);
L=L->adj;
head=tail=p;
p->adj=head;
while(L){
p=new Node(L->value,NULL);
L=L->adj;
p->adj=head;
head=p;
}
tail->adj=NULL;
return head;
}
int Compare(Node *minuend, Node *subtractor){
/*a>b return 1,a==b return 0,a<b return -1*/
int NumPowerMinuend=0,NumPowerSubtractor=0;
Node *tmpMinuend=minuend,*tmpSubtractor=subtractor;
while(tmpMinuend||tmpSubtractor){
if(NULL!=tmpMinuend){
NumPowerMinuend++;
tmpMinuend=tmpMinuend->adj;
}
if(NULL!=tmpSubtractor){
NumPowerSubtractor++;
tmpSubtractor=tmpSubtractor->adj;
}
}
if(NumPowerMinuend>NumPowerSubtractor){
return 1;
}
else if(NumPowerMinuend<NumPowerSubtractor){
return -1;
}
else{
tmpMinuend=Reverse(minuend),tmpSubtractor=Reverse(subtractor);
while(tmpMinuend&&tmpSubtractor){
if(tmpMinuend->value>tmpSubtractor->value){
return 1;
}
else if(tmpMinuend->value<tmpSubtractor->value){
return -1;
}
else{
return 0;
}
tmpMinuend=tmpMinuend->adj;
tmpSubtractor=tmpSubtractor->adj;
}
}
}
Node *CreatList(string str){
int len=str.length();
Node *p=