题目描述:
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
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
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.
中文理解:
给两个由0-9构成的字符串,然后字符串要么为"0",不存在"090"这种0开头的字符形式,给出两个字符串乘积的和,不允许使用已有的大整数运算函数库来实现。
解题思路:
首先考虑特殊情况,两个整数都为空或者某一个整数位0的情况直接返回结果,然后可以得到一般的情况下,两个整数相乘,结果的位数为两个数组位数之和或者位数之和-1,我们假设结果为为两个整数位数之和-1位。设置一个res[num1.length()+num2.length()-1],双层循环res[i+j]+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0')。得到的结果中数组下标越小数字代表的数位越大,然后从小处遍历将进位完善,最后得到最高位的进位,如果将结果保存在StringBuilder返回。
代码(java):
class Solution {
public String multiply(String num1, String num2) {
if(num1.length()==0 || num2.length()==0)return "";
if(num1.length()==1 && num1.equals("0") || num2.length()==1 && num2.equals("0"))return "0";
int []res=new int[num1.length()+num2.length()-1];
for(int i=0;i<num1.length();i++){
for(int j=0;j<num2.length();j++){
res[i+j]+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');
}
}
for(int i=res.length-1;i>0;i--){
res[i-1]+=res[i]/10;
res[i]=res[i]%10;
}
int head=res[0]/10;
res[0]=res[0]%10;
StringBuilder sb=new StringBuilder();
if(head!=0)sb.append(""+head);
for(int i=0;i<res.length;i++){
sb.append(""+res[i]);
}
return sb.length()==0 ? "0":sb.toString();
}
}