题目
分别使用顺序表和链表实现大数的乘法运算,顺序表或链表的每个节点中仅存储1位数宇。要求对输入宇符串有基本的容错检查,以#作为字符串的结束符号,并对比分析算法的时间和空间复杂度。
示例:输入:12345*9876#
输出:121919220
思路
大数乘法的核心代码如下。
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
ans[i + j] += num1[i] * num2[j];
}
}
其余的就看用什么类型处理了,我用了vector和list做处理,list由于不支持下标存取的,计算起来我嫌麻烦,封装了两个通过下标存取的函数。
void setAtPos(list<int> &lis, int pos, int number) {
auto iter = lis.begin();
while (pos--) {
iter++;
}
*iter = number;
}
int getAtPos(list<int> lis, int pos) {
auto iter = lis.begin();
while (pos--) {
iter++;
}
return *iter;
}
代码
具体代码贴这,仅供参考,大数加法、乘法都比较简单,大家有什么比较好的思路也可以评论区留言一下。
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
vector<int> vecMul(vector<int> v1, vector<int> v2) {
vector<int> vecResult(v1.size() + v2.size() - 1, 0);
for (int i = 0; i < v1.size(); i++) {
for (int j = 0; j < v2.size(); j++) {
vecResult[i + j] += v1[i] * v2[j];
}
}
for (int i = 0; i < vecResult.size(); i++) {
if (vecResult[i] > 9) {
if (i == vecResult.size() - 1) {
vecResult.push_back(0);
}
vecResult[i + 1] += vecResult[i] / 10;
vecResult[i] %= 10;
}
}
return vecResult;
}
void setAtPos(list<int> &lis, int pos, int number) {
auto iter = lis.begin();
while (pos--) {
iter++;
}
*iter = number;
}
int getAtPos(list<int> lis, int pos) {
auto iter = lis.begin();
while (pos--) {
iter++;
}
return *iter;
}
list<int> listMul(list<int> l1, list<int> l2) {
list<int> listResult(l1.size() + l2.size() - 1, 0);
auto iter1 = l1.begin();
for (int i = 0; i < l1.size(); i++, iter1++) {
auto iter2 = l2.begin();
for (int j = 0; j < l2.size(); j++, iter2++) {
setAtPos(listResult, i + j, getAtPos(listResult, i + j) + getAtPos(l1, i) * getAtPos(l2, j));
}
}
auto iter = listResult.begin();
for (int i = 0; i < listResult.size(); i++, iter++) {
if (getAtPos(listResult, i) > 9) {
if (i == listResult.size() - 1) {
listResult.push_back(0);
}
setAtPos(listResult, i + 1, getAtPos(listResult, i) / 10 + getAtPos(listResult, i + 1));
setAtPos(listResult, i, getAtPos(listResult, i) % 10);
}
}
return listResult;
}
int main() {
int curNumber;
bool isCorrect;
vector<int> v1, v2;
list<int> l1, l2;
while (1) {
char c;
curNumber = 1;
isCorrect = true;
cout << "请输入算式:";
while (1) {
cin >> c;
if (c >= '0' && c <= '9') {
if (curNumber == 1) {
v1.push_back(c - '0');
l1.push_front(c - '0');
}
else {
v2.push_back(c - '0');
l2.push_front(c - '0');
}
}
else if (c == '*') {
curNumber = 2;
}
else if (c == '#') {
break;
}
else {
cout << "输入错误,请重新输入正确的算式!" << endl;
isCorrect = false;
break;
}
}
if (isCorrect) {
reverse(v1.begin(), v1.end());
reverse(v2.begin(), v2.end());
vector<int> vecResult = vecMul(v1, v2);
cout << "vecResult:";
for (int i = vecResult.size() - 1; i >= 0; i--) {
cout << vecResult[i];
}
cout << endl;
list<int> listResult = listMul(l1, l2);
cout << "listResult:";
for (auto iter = listResult.rbegin(); iter != listResult.rend(); iter++) {
cout << *iter;
}
cout << endl;
}
v1.clear();
v2.clear();
l1.clear();
l2.clear();
}
}