原题: https://leetcode.com/problems/multiply-strings
这题思路没什么复杂的,就是设计一个数据结构存储每一位计算结果,然后处理一下进位逻辑,注意这里有连环进位,例如9999这种只要任意一个1加了1,那么就会像多米诺骨牌一样往前推,所以要用循环来处理
直接上代码:
package com.example.demo;
import java.util.Arrays;
public class MultiplyString {
private String printDigits(int[] dg){
StringBuilder sb = new StringBuilder();
boolean firstNonZero = false;
for(int i=dg.length-1;i>=0;i--){
if(dg[i]!=0){
firstNonZero = true;
}
if(firstNonZero){
sb.append(dg[i]);
}
}
return sb.toString();
}
public String multiply(String num1, String num2) {
if("0".equals(num1) || "0".equals(num2)){
return "0";
}
// i指向num1最后,j指向num2最后
// j不动,i向前扫,相乘,如果不大于10,则在记录如临时结果位置1, 用一个数组数据结构表示, 数组长度为num1+num2, 初始化全0
int[] d = new int[num1.length()+num2.length()];
Arrays.fill(d, 0);
for(int j = num2.length()-1;j>=0;j--){
for(int i = num1.length()-1;i>=0;i--){
int digit2 = Character.getNumericValue(num2.charAt(j));
int digit1 = Character.getNumericValue(num1.charAt(i));
// 相乘结果为:
int mul = digit1*digit2;
int curIndex = num2.length()-2-j+num1.length()-i;
if(mul<10){
incrementIndexBy(d, curIndex, mul);
}else{
incrementIndexBy(d, curIndex, mul%10);
incrementIndexBy(d, curIndex+1, mul/10);
}
}
}
return printDigits(d);
}
private void incrementIndexBy(int[] d, int index, int incVal){
int pi = index;
int inc = incVal;
while(d[pi]+inc>=10 && pi<d.length-1){
int nextInc = (d[pi]+inc)/10;
d[pi] = (d[pi]+inc)%10;
pi = pi + 1;
inc = nextInc;
}
d[pi] = d[pi]+inc;
}
public static void main(String[] args) {
String num1 = "123";
String num2 = "456";
//expect 56088
MultiplyString demo = new MultiplyString();
System.out.println(demo.multiply(num1, num2));
}
}