leetcode题目例题解析(六)
Multiply Strings
题目描述:
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
题意解析:
这道题的主要要求是求两个用字符串表示的大数的乘积,并把结果也用字符串表示出来
解题思路:
这里有一个思路就是,两个数分别为mn位,则两个数的乘积为m+n,m+n-1或者1位(其中一个数是0),我在这里解题的思路是,先不考虑进位,第一个数的k位和第二个数的l位的乘积先保存在结果的第k+l-1位,让两个数的每一位两两相乘,最后再从最低位到高位进位。
代码:
class Solution {
public:
string multiply(string num1, string num2) {
int ans[221];
string res;
for (int i = 0; i < 221; i++)
ans[i] = 0;
int a = num1.size();
int b = num2.size();
int k = 0;
//其中一个数是0,则直接返回0
if (a == 1&&num1[0] == '0'||b == 1&&num2[0] == '0')
return "0";
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
//这里注意把字符转换成数字
ans[i+j] += (num1[i] - '0')*(num2[j] - '0');
}
}
int temp[221];
//两个循环进行数组的翻转,上面得到的是从高位到低位的数组翻转之后方便进位
for (int i = 0; i < a + b - 1; i++) {
temp[a + b - i - 2] = ans[i];
}
for (int i = 0; i < a + b - 1; i++) {
ans[i] = temp[i];
}
//进位,每一位保留个位数,大于个位的进到高一位
for (int i = 0; i < a + b; i++) {
ans[i+1] += ans[i]/10;
ans[i] = ans[i]%10;
}
int s;
//判断结果是m+n位还是m+n-1位,上面已经排除了0的情况
if (ans[a + b - 1] != 0) {
s = a + b;
} else {
s = a + b - 1;
}
for (int i = s - 1; i >= 0; i--) {
res += (ans[i] + '0');//数字转换成字符
}
return res;
}
};
原题目链接:
https://leetcode.com/problems/multiply-strings/description/