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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容