问题描述

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"
示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"
说明:

num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/multiply-strings

解答

class Solution {
    //加到num1上 最后返回
    public void add(StringBuilder res, int temp2, int offset){
        int shiWei = ((int)temp2/10);
        int geWei = temp2%10;
        if(offset < res.length()){
            int ge = (int)(res.charAt(offset)-'0') + geWei;
            res.setCharAt(offset, (char)(ge%10+'0'));
            if(ge>=10)add(res, (int)(ge/10), offset+1);
        }else res.append(geWei);
        if(offset+1 < res.length()){
            int shi = (int)(res.charAt(offset+1)-'0') + shiWei;
            res.setCharAt(offset+1, (char)(shi%10+'0'));
            if(shi>=10)add(res, (int)(shi/10), offset+2);
        }else if(shiWei!=0)res.append(shiWei);
    }
    public String multiply(String num1, String num2) {
        StringBuilder res = new StringBuilder();
        int count=0;
        for(int i=num2.length()-1;i>=0;i--){
            int offset = count;
            int temp1 = (int)num2.charAt(i)-'0';
            for(int j=num1.length()-1;j>=0;j--){
                int temp2 = (int)num1.charAt(j)-'0';
                temp2 *= temp1;
                add(res, temp2, offset);
                offset++;
            }
            count++;
        }
        while(res.length()>1 && res.charAt(res.length()-1) == '0')res.deleteCharAt(res.length()-1);
        return res.reverse().toString();
    }
}