https://leetcode-cn.com/problems/multiply-strings/
这个题没啥好说的,我是直接暴力法,开了个n*m的数组,n为两个数字中最长的那个的长度,m是两个数字长度之和去存放计算过程中的中间数,然后再进行加法操作即可。时间效率比较低,空间效率也很低,但是AC了。。。
class Solution { public String multiply(String num1, String num2) { if(num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0){ return ""; } if("0".equals(num1) || "0".equals(num2)){ return "0"; } char[] str1 = num1.toCharArray(); char[] str2 = num2.toCharArray(); int totalLength = str1.length + str2.length; int bigger = Math.max(str1.length, str2.length); int[][] temp = new int[bigger][totalLength]; int count = 0; int layer = 0; int i = str1.length - 1; int j = str2.length - 1; for (; i >= 0; i--) { int k = 0; for (j = str2.length - 1; j >= 0; j--) { int realNum = (str2[j] - '0') * (str1[i] - '0'); temp[bigger - i - 1][totalLength - layer - 1 - k] = realNum % 10 + count; count = realNum / 10; k++; } temp[bigger - i - 1][totalLength - layer - 1 - k] = count; count = 0; layer++; } StringBuilder sb = new StringBuilder(); int sum = 0; for (j = totalLength - 1; j >= 0; j--) { for (i = 0; i < bigger; i++) { sum += temp[i][j]; } sum += count; count = sum / 10; while (sum >= 10) { sum %= 10; } sb.append(sum); sum = 0; } if (count != 0) { sb.append(count); } return sb.reverse().toString().replaceFirst("^0*",""); } }
评论区中有更快的方法,直接开一维数组存中间过程的数即可,根本用不着吧所有中间过程的数保存下来后再做加法运算。。。。。。。。