LeetCode-Multiply Strings

Description:
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"

Note:

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contain only digits 0-9.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

题意:计算两个用字符串表示的数的乘积;

解法:实际上这道题要我们解决的是大数的乘法;

  • 我们首先将两个字符串转为两个整数数组digit1和digit2(逆序,这样低位在首部);
  • 之后,我们进行乘法运算, r e s u l t [ i + j ] + = d i g i t 1 [ i ] ∗ d i g i t 2 [ j ] result[i + j] += digit1[i] * digit2[j] result[i+j]+=digit1[i]digit2[j],即对digit2中的所有每一个元素,都乘以digit1中的所有元素存储在对应位置上(注意,此时并没有累加进位);
  • 现在,我们需要对所得的结果result进行进位的累加,对每个大于等于10的元素,累加进位到后一个元素上,并且当前位进行取余;
  • 最后,我们需要跳过result中的前导0后得到result有效数字的长度,逆序取出即是最后的结果;
Java
class Solution {
    public String multiply(String num1, String num2) {
        int[] digit1 = new int[num1.length()];
        int[] digit2 = new int[num2.length()];
        int[] result = new int[num1.length() + num2.length() + 1];
        
        for (int i = num1.length() - 1, j = 0; i >= 0; i--) digit1[j++] = num1.charAt(i) - '0';
        for (int i = num2.length() - 1, j = 0; i >= 0; i--) digit2[j++] = num2.charAt(i) - '0';
        
        for (int i = 0; i < digit1.length; i++) {
            for (int j = 0; j < digit2.length; j++) {
                result[i + j] += digit1[i] * digit2[j];
            }
        }
        for (int i = 0; i < result.length; i++) {
            if (result[i] >= 10) {
                result[i + 1] += result[i] / 10;
                result[i] %= 10;
            }
        }
        int len = result.length - 1;
        while (len >= 0 && result[len] == 0) len--;
        StringBuilder num = new StringBuilder();
        while (len >= 0) num.append(result[len--]);
        
        return num.length() == 0 ? "0" : num.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值