力扣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.将乘积加到 resp2,同时处理进位。
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();
    }
}
相关推荐
jktantan26 分钟前
注解式脱敏:用 Jackson 的 ContextualSerializer 做字段级策略(一)
spring boot·后端·算法·spring cloud·系统架构
Dream it possible!13 小时前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊14 小时前
算法之双指针系列(一)
算法·leetcode
十二14 小时前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
小此方15 小时前
[算法实战论:动态规划]回文串问题的dp解法,回文串问题的母题,以及以此为基础的派生题
算法·动态规划
Pniubi15 小时前
力扣560.和为k的子数组
算法·leetcode·职场和发展
D e re k ZH16 小时前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
Pniubi16 小时前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
東隅已逝,桑榆非晚19 小时前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
Eyfcom19 小时前
〖物联网终端实战 01〗UWB 室内高精度定位:仓储 AGV 与人员的厘米级轨迹追踪
物联网·算法·物流系统·快递系统·跨境物流快递系统·物联网终端实战