LeetCode 刷题之路 Multiply Strings

本文介绍了一种解决大数乘法问题的方法,通过字符串表示的大整数进行相乘,并返回同样以字符串形式表达的乘积。文中提供了两种实现思路:一是通过逐位相乘再进位的方式;二是优化了进位过程,避免了额外的最高位进位计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

这题是大数乘法问题, 所以很自然的想到模拟我们平时乘法做法采用拆分乘数,然后乘法累加。

class Solution {
    public String multiply(String num1, String num2) {

        if(num1.equals("0") || num2.equals("0")){
            return "0";
        }
        int length1 = num1.length();
        int length2 = num2.length();
        int[] res = new int[length1+length2];

        StringBuffer result = new StringBuffer();
        for(int i = length1-1; i>=0; i--){
            for(int j = length2-1; j>=0; j--){
                int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
                int cur = i + j;
                int pre = cur + 1;
                int sum = mul + res[pre];

                res[cur] += sum / 10;
                res[pre] = sum % 10;
            }
        }
        for (int i=0; i<res.length; ++i){
            if (i==0 && res[i]==0) continue;
            result.append(res[i]);
        }
        return result.toString();
    }
}

看到别人用同一种方法写的,但是每次添加位变成[i+j+1], 目的是避免算出的最高位需要进位。

class Solution {
    public String multiply(String num1, String num2) {

        if(num1.equals("0") || num2.equals("0")){
            return "0";
        }
        int length1 = num1.length();
        int length2 = num2.length();
        int[] res = new int[length1+length2];

        StringBuffer result = new StringBuffer();
        for(int i = length1-1; i>=0; i--){
            for(int j = length2-1; j>=0; j--){
                res[i+j+1] += (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
            }
        }
        for (int i=res.length-1; i>0; i--){
            if (res[i]>9){
                res[i-1] += res[i]/10;
                res[i] %=10;
            }
        }
        for (int i=0; i<res.length; ++i){
            if (i==0 && res[i]==0) continue;
            result.append(res[i]);
        }
        return result.toString();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值