LeetCode 43. Multiply Strings 字符串相乘(Java)

题目:

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.

解答:

这道题的整体思路与我们通过竖式计算的方法基本相同,即从一个数的最低位开始,依次与另一个数相乘。
通过竖式相乘的过程和最终结果我们可以发现,若第一个数的第 i 位与第二个数的第 j 位相乘,得到的数对应最终计算结果的第 i+j 位。
为了简化计算过程,我们可以先省略进位,在得到相乘结果的数组后,再从最低位开始依次进行进位处理。

			1	2	3
×			4	5	6
__________________________
			6	12	18
	+	5	10	15
+	4	8	12
——————————————————————————
	4	13	28	27	18   (数组 res 存储计算结果)								
						↓(进位处理)
	5	6	0	8	8   (最终结果)

综上,具体思路如下:

  1. 创建 res 数组用于存储相乘结果。一个 m 位的数与一个 n 位的数相乘,则结果最高为 m+n-1 位。(第一次提交时,创建数组长度为 m+n,则会导致错误,如 2*3,最低位会被初始化为0,计算结果会错为 60)
  2. 通过 ASCII 码相减 num1.charAt(i) - 48将数字字符转换为 int 类型,并逐位相乘,相加至对应位置
  3. 从低位开始对 res 中结果进行逐位进位,i 位置对应的最终计算结果为 res[i]%10,res/10 为进位结果并加至高一位
  4. 通过 StringBuffer.append() 方法将数组中结果转为字符串类型并输出
class Solution {
    public String multiply(String num1, String num2) {
        if(num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        int len1 = num1.length();
        int len2 = num2.length();
        int[] res = new int[len1+len2-1];
        //逐位相乘
        for(int i=0; i<len1; i++) {
            for(int j=0; j<len2; j++) {
                int one = num1.charAt(i) - 48;
                int two = num2.charAt(j) - 48;
                res[i+j] += one * two;
            }
        }
        //进位处理
        for(int i=res.length-1; i>0; i--) {
            res[i-1] += res[i]/10; 
            res[i] %= 10; 
        }
        StringBuffer str = new StringBuffer();
        for(int i=0; i<res.length; i++) {
            str.append(res[i]);
        }
        return str.toString();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值