關於兩個長整數相乘的實現
題目:實現兩個長整數相乘的演算法。
此程式碼可實現任意長度的兩個數相乘,實現方法採用單向連結串列。
以下是我的程式碼.
備註:此程式碼有參考網上的程式碼。
#include "stdafx.h"
#include <iostream>
using namespace std;
#define MAX 10000
structNode
{
intdata;
Node*next;
};
void output(Node *head)
{
if(!head->next && !head->data)
return;
output(head->next
cout << head->data;
}
voidMul_Operation(char *str1, char *str2)
{
char*ap = str1;
char *bp = str2;
Node*head = NULL;
head = new Node;
head->data = 0;
head->next = NULL;//頭
Node *p,*q = head,*p1;
int temp = 0,temp1,bbit;
while (*bp)//若乘數不為空,繼續.
{
p = q->next;
p1 = q;
bbit = *bp - 48;//把當前位轉為整型
while(*ap||temp)//若被乘數不空,繼續
{
if(!p)//若要操作的結點為空,申請之
{
p = new Node;
p->data = 0;
p->next = 0;
p1->next = p;
}
if(*ap == 0)
temp1 = temp;
else
{
temp1 = (p1->data) + (*ap - 48) * bbit + temp;
ap++;
}
p1->data = temp1 % 10;//留當前位
temp = temp1 / 10;//進位以int的形式留下.
p1 = p;
p = p->next;//被乘數到下一位
}
ap = a
bp++;
q = q->next;//q進下一位
}
p = head;
cout << "The result is: ";
output(p);//顯示
cout << endl;
while(head)//釋放空間
{
p = head-> next;
delete head;
head = p;
}
}
int main()
{
cout << "請輸入兩個數" << endl;
chartest1[MAX],test2[MAX];
cin >> test1 >> test2;
Mul_Operation(strrev(test1),strrev(test2));//strrev是字串反轉函式
return0;
}