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.

题目解析:
1.二个字符串相乘;
2.字符转换成数字,即该字符 减去 字符 ‘0’;
3.数字相乘基本法则,乘数从最低位开始,乘以被乘数;
4.二个数字相乘,最大长度,即二个乘数 长度和。

例:
在这里插入图片描述
代码:

class Solution {
    public String multiply(String num1, String num2) {
        if(num1 == null || num2 == null)
        {
            return "";
        }
        int len1 = num1.length();
        int len2 = num2.length();
        int[] res = new int[len1 + len2];
        for(int i = len1 - 1;i >= 0; i--)
        {
            int digit1 = num1.charAt(i) - '0';
            for(int j = len2 -1;j>=0;j--)
            {
                int digit2 = num2.charAt(j) - '0';
                int sum = digit1 * digit2 + res[i+j+1];//暂存相乘数值,需加上低位的值
                res[i+j] += sum/10;//十位数,存在高位
                res[i+j+1] = sum%10;//个位数,存在低位
            }
        }
        
        StringBuilder sb = new StringBuilder();//数组值转化成字符串
        for(int i = 0;i < res.length;i++)
        {
            if(sb.length() == 0 && res[i] == 0)//过滤数组首位是0,例0123,输出123
            {
                continue;
            }
            sb.append(res[i]);
        }
        
        return sb.length() == 0 ? "0" : sb.toString();
    }
}

性能:
在这里插入图片描述

总结:
知识点1:字符转换成数字;
知识点2:二数相乘基本法则抽象成程序。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值