前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 题目解析之 Multiply Strings

Leetcode 题目解析之 Multiply Strings

原创
作者头像
ruochen
发布2022-01-15 12:18:20
1.2K0
发布2022-01-15 12:18:20
举报

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

代码语言:javascript
复制
    public String multiply(String num1, String num2) {
        if (num1 == null || num2 == null) {
            return "";
        }
        int[] paper = new int[num1.length() + num2.length()];
        char[] _num1 = num1.toCharArray();
        char[] _num2 = num2.toCharArray();
        for (int i = 0; i < _num1.length; i++) {
            for (int j = 0; j < _num2.length; j++) {
                paper[paper.length - (i + j + 2)] += (_num1[i] - '0')
                        * (_num2[j] - '0');
            }
        }
        // add
        for (int i = 0; i < paper.length - 1; i++) {
            paper[i + 1] += paper[i] / 10;
            paper[i] %= 10;
        }
        String s = "";
        for (int i = paper.length - 1; i > 0; i--) {
            if ("" == s && paper[i] == 0) {
                continue;
            }
            s += paper[i];
        }
        s += paper[0];
        return s;
    }
    // can't be accepted in leetcode
    public String multiply2(String num1, String num2) {
        if (num1 == null || num2 == null) {
            return "";
        }
        BigInteger n1 = new BigInteger(num1);
        BigInteger n2 = new BigInteger(num2);
        return n1.multiply(n2).toString();
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档