力扣43. 字符串相乘

Problem: 43. 字符串相乘

文章目录

题目描述

思路及解法

1.初始化和结果数组:

1.1.获取 num1 和 num2 的长度。

1.2.初始化一个 int 数组 res,长度为 len1 + len2,用于存储中间计算结果。因为两个数相乘的结果最多是 len1 + len2 位。
2.逐位相乘:
2.1.从两个字符串的最低位(个位)开始逐位相乘。

2.2.计算乘积 mul,对应到结果数组的两个位置 p1 和 p2。p1 是进位位置,p2 是当前位位置。

2.3.将乘积加到 res[p2],同时处理进位。
3.处理结果数组前导零:遍历 res 数组,跳过前导零,找到第一个非零元素的位置。
4.构建最终结果字符串:
4.1.使用 StringBuilder 将结果数组中的数字逐个转换为字符并拼接成字符串。

4.2.如果结果字符串为空,返回 "0";否则返回拼接好的字符串。

复杂度

时间复杂度:

O ( M × N ) O(M \times N) O(M×N);其中 M M M是数组num1的长度, N N N是数组num2的长度

空间复杂度:

O ( M + N ) O(M + N) O(M + N)

Code

java 复制代码
class Solution {
    /**
     * Multiply Strings
     *
     * @param num1 Given array
     * @param num2 Given array
     * @return String
     */
    public String multiply(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        // The result has a maximum of len1 + len2 bits
        int[] res = new int[len1 + len2];
        // Multiply digit by digit starting from the ones digit
        for (int i = len1 - 1; i >= 0; --i) {
            for (int j = len2 - 1; j >= 0; --j) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                // The product is in the index position of res
                int p1 = i + j;
                int p2 = i + j + 1;
                // Overlay to res
                int sum = mul + res[p2];
                res[p2] = sum % 10;
                res[p1] += sum / 10;
            }
        }
        // Result prefix possible stored 0(unused bits)
        int i = 0;
        while (i < res.length && res[i] == 0) {
            i++;
        }
        // Converts the result to a string
        StringBuilder str = new StringBuilder();
        for (; i < res.length; ++i) {
            str.append((char) ('0' + res[i]));
        }
        return str.length() == 0 ? "0" : str.toString();
    }
}
相关推荐
良月澪二3 分钟前
CSP-S 2021 T1廊桥分配
算法·图论
wangyue41 小时前
c# 线性回归和多项式拟合
算法
&梧桐树夏1 小时前
【算法系列-链表】删除链表的倒数第N个结点
数据结构·算法·链表
QuantumStack1 小时前
【C++ 真题】B2037 奇偶数判断
数据结构·c++·算法
今天好像不上班1 小时前
软件验证与确认实验二-单元测试
测试工具·算法
wclass-zhengge2 小时前
数据结构篇(绪论)
java·数据结构·算法
何事驚慌2 小时前
2024/10/5 数据结构打卡
java·数据结构·算法
结衣结衣.2 小时前
C++ 类和对象的初步介绍
java·开发语言·数据结构·c++·笔记·学习·算法
大二转专业4 小时前
408算法题leetcode--第24天
考研·算法·leetcode
凭栏落花侧4 小时前
决策树:简单易懂的预测模型
人工智能·算法·决策树·机器学习·信息可视化·数据挖掘·数据分析