Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = “2”, num2 = “3”
Output: “6”
Example 2:
Input: num1 = “123”, num2 = “456”
Output: “56088”
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
题目解析:
1.二个字符串相乘;
2.字符转换成数字,即该字符 减去 字符 ‘0’;
3.数字相乘基本法则,乘数从最低位开始,乘以被乘数;
4.二个数字相乘,最大长度,即二个乘数 长度和。
例:
代码:
class Solution {
public String multiply(String num1, String num2) {
if(num1 == null || num2 == null)
{
return "";
}
int len1 = num1.length();
int len2 = num2.length();
int[] res = new int[len1 + len2];
for(int i = len1 - 1;i >= 0; i--)
{
int digit1 = num1.charAt(i) - '0';
for(int j = len2 -1;j>=0;j--)
{
int digit2 = num2.charAt(j) - '0';
int sum = digit1 * digit2 + res[i+j+1];//暂存相乘数值,需加上低位的值
res[i+j] += sum/10;//十位数,存在高位
res[i+j+1] = sum%10;//个位数,存在低位
}
}
StringBuilder sb = new StringBuilder();//数组值转化成字符串
for(int i = 0;i < res.length;i++)
{
if(sb.length() == 0 && res[i] == 0)//过滤数组首位是0,例0123,输出123
{
continue;
}
sb.append(res[i]);
}
return sb.length() == 0 ? "0" : sb.toString();
}
}
性能:
总结:
知识点1:字符转换成数字;
知识点2:二数相乘基本法则抽象成程序。