LeetCode算法入门- Multiply Strings -day18

LeetCode算法入门- Multiply Strings -day18

  1. 题目介绍

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.

  1. 题目分析
    解题思想在于这个图:
    在这里插入图片描述

通过上述的推导我们可以发现num1[i] * num2[j]的结果将被保存到 [i + j, i + j + 1] 这两个索引的位置。其中它们的个位数保存在 (i + j + 1) 的位置,十位数保存在 (i + j) 的位置。所以我们可以定义一个数组 pos[m + n] ,它的长度为两个数组的长度。只是它们的计算不需要把它们给反转过来。每次我们有num1[i] * num2[j]的时候先取得 pos1 = i + j, pos2 = i + j + 1。这样得到的值是
sum = num1[i] * num2[j] + pos[pos2]。按照前面的计算规则,。pos[pos1] = pos[pos1] + sum/10; pos[pos2] = sum % 10;

  1. Java实现
class Solution {
    public String multiply(String num1, String num2) {
        int m = num1.length();
        int n = num2.length();
        //定义这个数组来存储最后结果的每一位
        int[] pos = new int[m+n];
        
        //从最右边开始,所以是m-1
        for(int i = m -1; i >= 0; i--){
            for(int j = n -1; j >= 0; j--){
                int mul  = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int p1 = i + j;
                int p2 = i + j + 1;
                //这里进行运算,最后需要用到的是数组每个下标的值,下面不是很理解
                int sum = mul + pos[p2];
                pos[p1] = pos[p1] + sum/10;
                pos[p2] = sum % 10;
                
            }
        }
        StringBuilder sb = new StringBuilder();
        for(int p : pos){
            //排除高位数为0的情况
            if(sb.length() == 0 && p == 0){
                continue;
            }
            else{
                sb.append(p);
            }
        }
        //排除长度为0的情况
        if(sb.length() == 0)
            return "0";
        else{
            return sb.toString();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值