问题描述:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
问题分析:
如题所述,需要将两个字符串的数字进行相乘,然后结果再用字符串输出。字符串乘法能突破数据类型计算两个长值的数字相乘的限制,具有实际意义。
实现思路可以按照手写乘法的方式来实现,即使用两个数字的各位数值进行逐位相乘,保存在一个结果数组中,再对数组中各数值进行进位处理。最后根据结果数组的值输出字符串即可。
代码如下:
class Solution {
public:
string multiply(string num1, string num2) {
int len1 = num1.length();
int len2 = num2.length();
reverse(num1.begin(),num1.end());
reverse(num2.begin(),num2.end());
int data[len1+len2]={0};
for(int i=0;i
0)
{
index--;
if(!flag&&data[index]==0)continue;
else
{
flag = true;
result += (char)(data[index]+'0');
}
}
if(!flag) return "0";
return result;
}
};
运行时间:
9ms