1. 程式人生 > 實用技巧 >43. 字串相乘-字串-中等難度

43. 字串相乘-字串-中等難度

問題描述

給定兩個以字串形式表示的非負整數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(); } }