题目

43. 字符串相乘

题解




代码

public class code43 {
    public static String multiply(String num1, String num2) {
        int n1 = num1.length() - 1;
        int n2 = num2.length() - 1;
        if (n1 < 0 || n2 < 0) {
            return "";
        }
        // 常识两数相乘不会超过两者长度和
        int mul[] = new int[n1 + n2 + 2];

        for (int i = n1; i >= 0; i--) {
            for (int j = n2; j >= 0; j--) {
                int val = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                val += mul[i + j + 1]; // 先把乘积加到低位, 再判断是否有新的进位

                mul[i + j] += val / 10; // 求高位
                mul[i + j + 1] = val % 10; // 求低位
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = 0;
        // 去掉前导0
        while (i < mul.length - 1 && mul[i] == 0) {
            i++;
        }
        while (i < mul.length) {
            sb.append(mul[i]);
            i++;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(multiply("123456", "0"));
        System.out.println(multiply("25", "4"));
        System.out.println(multiply("2", "3"));
        System.out.println(multiply("123", "456"));
    }
}

参考

  1. Python 字符串暴力模拟竖式乘法计算过程
  2. LeetCode : 43. 字符串相乘(Multiply Strings)解答
  3. 43. 字符串相乘
  4. [LeetCode] Multiply Strings 字符串相乘
  5. Leetcode 43:字符串相乘(超详细的解法!!!)
  6. [LeetCode] Multiply Strings 字符串相乘