LeetCode 43 字符串相乘

Leetcode 43 字符串相乘

给定两个代表无符号整数的字符串num1、num2,求两字符串表示的整数的乘积的字符串。

执行用时:3 ms, 在所有 Java 提交中击败了94.87%的用户
内存消耗:40 MB, 在所有 Java 提交中击败了39.71%的用户


方法一: 基于传统的竖版乘法运算规则,遍历num2的每一位与num1相乘,过程示例如下

class Solution {
    public String multiply(String num1, String num2) {
        //某一乘数为0,则结果为0
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int m = num1.length(), n = num2.length();
        //存放每次乘法的结果(num1第i位、num2第j位)
        int[] ansArr = new int[m + n];
        for (int i = m - 1; i >= 0; i--) {
            int x = num1.charAt(i) - '0';
            for (int j = n - 1; j >= 0; j--) {
                int y = num2.charAt(j) - '0';
                ansArr[i + j + 1] += x * y;
            }
        }
        //所有乘积汇总求和(???)
        for (int i = m + n - 1; i > 0; i--) {
            ansArr[i - 1] += ansArr[i] / 10;
            ansArr[i] %= 10;
        }
        int index = ansArr[0] == 0 ? 1 : 0;
        StringBuffer ans = new StringBuffer();
        while (index < m + n) {
            ans.append(ansArr[index]);
            index++;
        }
        return ans.toString();
    }
}
原文地址:https://www.cnblogs.com/CodeSPA/p/13494734.html