43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
1、The length of both num1 and num2 is < 110.
2、Both num1 and num2 contains only digits 0-9.
3、Both num1 and num2 does not contain any leading zero.
4、You must not use any built-in BigInteger library or convert the inputs to integer directly.

public class Solution {
    public String multiply(String num1, String num2) {
        int len1 = num1.length(),len2 = num2.length();
        int[] num = new int[len1+len2];
        int n = len1+len2;
        for(int i=len1-1;i>=0;i--)
           for(int j=len2-1;j>=0;j--)
           {
               num[i+j+1] += (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
           }
        for(int i=n-1;i>0;i--)
        {
            int carry = num[i]/10;
            num[i] %= 10;
            num[i-1] += carry;
        }
        String result = "";
        boolean flag = false;
        for(int i=0;i<n;i++)
        {
            if(flag == false&&num[i] == 0)
                continue;
            else
            {
                result += num[i];
                flag = true;
            }
        }
        if(result.equals(""))
           return "0";
        return result;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容