43. Multiply Strings

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

Solution:模拟乘法计算,对应位结果加到结果数组pos

Time Complexity: O(m * n) Space Complexity: O(m + n)

屏幕快照 2017-08-31 下午9.18.03.png

Solution Code:

class Solution {
    public String multiply(String num1, String num2) {
        int m = num1.length(), n = num2.length();
        int[] pos = new int[m + n];

        for(int j = n - 1; j >= 0; j--) {
            for(int i = m - 1; i >= 0; i--) {
                int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); 
                int p1 = i + j, p2 = i + j + 1;
                int sum = mul + pos[p2];

                pos[p1] += sum / 10;
                pos[p2] = (sum) % 10;
            }
        }  

        // prepare the result
        StringBuilder sb = new StringBuilder();
        for(int p : pos) 
            if(!(sb.length() == 0 && p == 0)) sb.append(p);
        return sb.length() == 0 ? "0" : sb.toString();
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 题目: 给定两个字符串十进制数字,给出字符串为他们的乘积。要求如下: 禁止使用内置大数算法。 字符串长度110 输...
    linanwx阅读 3,890评论 0 0
  • Given two non-negative integers num1 and num2 represented...
    Jeanz阅读 3,437评论 0 0
  • 闪电划破黢黑的夜空,穿透厚重的窗帘,惊雷蓦地炸开,大地似乎都在战栗。莫名地,慌乱地从床上爬起来,惊恐地睁大眼睛。窗...
    甑容儿阅读 2,854评论 0 1
  • 放暑假了,我们班有些人就解脱了。但是我的末日才刚刚开始。因为要练田径。每一次跑步,不知道为什么,我就是跑不动。一...
    黎馨蕊阅读 2,166评论 0 1