链接:https://leetcode-cn.com/problems/multiply-strings
给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。
示例 1:
输入: num1 = “2”, num2 = “3”
输出: “6”
示例 2:
输入: num1 = “123”, num2 = “456”
输出: “56088”
说明:
num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。
public static String mutiply(String num1,String num2) {
int n1=num1.length(),n2=num2.length();
int[]products=new int[n1+n2];
for (int i = n1-1; i >=0; i--) {
for (int j = n2-1; j >=0; j--){
int d1=num1.charAt(i)-'0';
int d2=num2.charAt(j)-'0';
products[i+j+1]+=d1*d2;
}
}
int carry=0;
for (int i = products.length-1; i >=0; i--) {
int tmp= (products[i]+carry)%10;
carry=(products[i]+carry)/10;
products[i]=tmp;
}
StringBuilder sb=new StringBuilder();
for(int num:products)sb.append(num);
while(sb.length()!=0 && sb.charAt(0)=='0')sb.deleteCharAt(0);
return sb.length()==0?"0":sb.toString();
}
//测试类
class StringMutiply{
public static void main(String[] args) {
String num1="123",num2="456";
String res =mutiply(num1,num2);
//输出 56088
System.out.println(res);
}
}