1. 问题描述:
给定两个非负整数(不含前导 0) A 和 B,请你计算 A × B 的值。
输入格式
共两行,第一行包含整数 A,第二行包含整数 B。
输出格式
共一行,包含 A×B 的值。
数据范围
1 ≤ A的长度 ≤ 100000,
0 ≤ B ≤ 10000
输入样例:
2
3
输出样例:
6
来源:https://www.acwing.com/problem/content/description/795/
2. 思路分析:
这道题目属于高精度乘法的模板题,我们可以将第一个输入的数字a的每一位抠出来存储到列表A中,然后将A中的每一位与b相乘,最后处理一下进位的问题即可。对于python语言来说其实可以不用高精度乘法,直接使用两个数字相乘也不会溢出,而且直接计算的速度更快,而对于其他语言来说则需要使用高精度乘法才不会出现溢出的情况。
3. 代码如下:
c++代码(c++与python的运行速度真的是天差地别啊,c++只用49ms就过了):
#include <iostream>
#include <vector>
using namespace std;
vector <int> mul(vector <int> & A, int b) {
vector <int> C;
int t = 0;
for (int i = 0; i < A.size(); i ++) {
t += A[i] * b;
C.push_back(t % 10);
t /= 10;
}
while (t) {
C.push_back(t % 10);
t /= 10;
}
while (C.size() > 1 && C.back() == 0) C.pop_back();
return C;
}
int main() {
string a;
int b;
cin >> a >> b;
vector <int> A;
for (int i = a.size() - 1; i >= 0; i --) A.push_back(a[i] - '0');
auto C = mul(A, b);
for (int i = C.size() - 1; i >= 0; i --) {
cout << C[i];
}
return 0;
}
python代码(使用高精度的超时了,但是直接输出A * B确通过了,python果然不会溢出):
from typing import List
class Solution:
# a中的每一位乘以b
def mul(self, a: List[int], b: int):
c = list()
i = t = 0
while i < len(a) or t:
if i < len(a):
t += a[i] * b
c.append(t % 10)
t //= 10
i += 1
return c
def process(self):
a = int(input())
b = int(input())
A = list()
# 将a的每一位抠出来存储到A中
while a > 0:
A.append(a % 10)
a //= 10
C = self.mul(A, b)
# 输出结果
for i in range(len(C) - 1, -1, -1):
print(C[i], end="")
if __name__ == "__main__":
Solution().process()
优化之后还是超时了:
class Solution:
def process(self):
a = int(input())
b = int(input())
c = list()
t = 0
while a > 0 or t > 0:
t += (a % 10) * b
c.append(t % 10)
t //= 10
a //= 10
for i in range(len(c) - 1, -1, -1):
print(c[i], end="")
if __name__ == "__main__":
Solution().process()
通过代码(果然python对于大数而言不用搞什么高精度相乘或者相加更快):
if __name__ == "__main__":
a = int(input())
b = int(input())
print(a * b)