LeetCode T43 Multiply Strings

题目地址

https://leetcode-cn.com/problems/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.

Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= num1.length, num2.length <= 200
  • num1 and num2 consist of digits only.
  • Both num1 and num2 do not contain any leading zero, except the number 0 itself.

思路

题目说了不让用BigInterger等类把字符串直接转为整数。
然后呢,数字字符串的长度足足有110。
那就老老实实模拟乘法吧。

步骤:

  1. 模拟每位乘法,记录每个位的数字,先不管进位
  2. 处理每个进位

详见代码注释~~

题解

class Solution {
    public String multiply(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
		//如果有从乘数为0返回0
        if(len1==1&&num1.charAt(0)=='0') return "0";
        if(len2==1&&num2.charAt(0)=='0') return "0";

        int[] res_i = new int[500];
        String res_s = "";
        //下面这个循环计算每个位上的结果(没进位)
        for(int i=0;i<len1;i++)
            for(int j=0;j<len2;j++){
                res_i[i+j] += (num1.charAt(len1-i-1)-'0')*(num2.charAt(len2-j-1)-'0');
            }
        //处理进位
        for(int i=0;i<len1+len2;++i) {
            if(res_i[i]>=10){
                res_i[i+1]+=res_i[i]/10;
                res_i[i] = res_i[i]%10;
            }
        }
        //len1位的数和len2位的数相乘的结果可能为len1+len2位或len1+len2-1位,这里做个判断
        int los=0;
        if(res_i[len1+len2-1]==0) los = 1;
		//将保存在数组中的结果转为字符串
        for(int i=0;i<len1+len2-los;++i) {
            res_s = res_i[i] + res_s;
        }
        return res_s;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值