跳到正文

题解

题解:P1303 A*B Problem

Lily_Celeste约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月21日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
获赞
7
题目
P1303

版本

  1. v1当前

这是一道高精度乘法的模板题。

我们需要模拟列竖式的过程。

Part1

输入两个乘数,将字符转换成数字倒着放入数组中。

C++
cin >> a1 >> b1;
int la = a1.size();
int lb = b1.size();
for(int i = 0;i < la;i++){
    a[i] = a1[la - i - 1] - '0';
}
for(int i = 0;i < lb;i++){
    b[i] = b1[lb - i - 1] - '0';
}

Part2

双重循环,模拟手动列竖式的过程,将答案存入一个数组中。

C++
for(int i = 0;i < lb;i++){
		for(int j = 0;j < la;j++){
			c[i + j] += a[j] * b[i];
		}
}

Part3

处理进位,如果当前的值大于九,就向前进位。

C++
for(int i = 0;i < la + lb;i++){
    if(c[i] > 9){
      	c[i + 1] += c[i] / 10;
      	c[i] %= 10;
    }
}

Part4

去除前导0。

代码
lc = la + lb;
while(c[lc - 1] == 0 && lc > 1){
    lc--;
}

Part5

输出 cc 数组即可。

C++
for(int i = lc - 1;i >= 0;i--){
    cout << c[i];
}

Code

C++
#include<bits/stdc++.h>
using namespace std;

const int N = 1e4;
string a1, b1;
int a[N + 5], b[N + 5], c[N + 5];
int x, la, lb, lc;

int main (){
    cin >> a1 >> b1;
    int la = a1.size();
	int lb = b1.size();
    for(int i = 0;i < la;i++){
    	a[i] = a1[la - i - 1] - '0';
	}
    for(int i = 0;i < lb;i++){
    	b[i] = b1[lb - i - 1] - '0';
	}
	for(int i = 0;i < lb;i++){
		for(int j = 0;j < la;j++){
			c[i + j] += a[j] * b[i];
		}
	}
    for(int i = 0;i < la + lb;i++){
    	if(c[i] > 9){
			c[i + 1] += c[i] / 10;
			c[i] %= 10;
		}
	}
	lc = la + lb;
    while(c[lc - 1] == 0 && lc > 1){
    	lc--;
	}
    for(int i = lc - 1;i >= 0;i--){
    	cout << c[i];
	}
    cout << "\n";
    return 0;
}

感谢观看。

原文
存档评论5 条抓取于