时间: 2020-11-23|68次围观|0 条评论

题目:

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.

思路:

做乘法

package manipulation;

public class MultiplyStrings {

    public String multiply(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        int len = len1 + len2;
        int[] res = new int[len];
        for (int i = len1 - 1; i >= 0; --i) {
            for (int j = len2 - 1; j >= 0; --j) {
                multiply(num1, i, num2, j, res, len);
            }
        }
        StringBuilder sb = new StringBuilder();
        int i = len - 1;
        while (i >= 0 && res[i] == 0) --i;
        
        if (i == -1) sb.append('0');
        for (; i >= 0; --i) {
            sb.append((char)(res[i] + '0'));
        }
        
        return sb.toString();
    }
    
    private void multiply(String num1, int i, String num2, int j, int[] res, int len) {
        int m = num1.charAt(i) - '0';
        int n = num2.charAt(j) - '0';
        int value = m * n;
        int index = len - i - j - 2;
        res[index] = res[index] + value;
        res[index + 1] = res[index + 1] + res[index] / 10;
        res[index] = res[index] % 10;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiplyStrings m = new MultiplyStrings();
        System.out.println(m.multiply("11", "11"));
    }

}

 

转载于:https://www.cnblogs.com/null00/p/5075539.html

原文链接:https://blog.csdn.net/weixin_30342827/article/details/97555526

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《LeetCode – Multiply Strings
   

还没有人抢沙发呢~