leetcode-Multiply Strings

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.
    • Converting the input string to integer is NOT allowed.
    • You should NOT use internal library such as BigInteger.

解析:主要是数组位置和乘法位置的关系图:

Multiplication

代码解析:package leetcode;

/*
 * 题目主要考察字符串的乘法运算!!!
 * 关键步骤:
 * 1、找好每一步乘法结果与结果数组(pos[])对应起来。每一次只在pos数组中进行运算!!!这样就涉及到两个char[]和一个int[]!!!
 * 2、每一步乘法的结果应该加上以前的进位!!那么变量有:进位变量pos[p2],当前存储乘法结果的变量cures,然后将这个结果拆分成十位+个位,存在pos两个位置里,然后循环的时候,同时往前走一步,p2 ->p1位置。
 * 3、最后构造String的时候使用StringBuilder,主要是用来判断第一个数是否为0!!
 */
public class MultiplyStrings {

    public static String multiply(String num1, String num2) {
        char[] ch1 = num1.toCharArray();
        char[] ch2 = num2.toCharArray();
        int len1 = num1.length();
        int len2 = num2.length();
        int[] pos = new int[len1 + len2];

        for (int j = len2 - 1; j >= 0; j--)
            for (int i = len1 - 1; i >= 0; i--) {
                int cures = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                // 下标是往前运动的
                int p1 = i + j, p2 = i + j + 1;
                // 每一步的运算的子结果,为什么是p2?
                // 因为:这里的p2就是下一个循环的p1,而p1指向更前的位置
                // 在下一个循环加进位!!!!!!
                int sum = cures + pos[p2];

                // 对每个相邻的位进行运算
                pos[p1] += sum / 10;
                // 存储后面那一位(不再变化),前面的位很有可能向前进位,所有要+=
                pos[p2] = sum % 10;
            }
        // 这一步:array->string,有很多方法,其实底层都是构造string;
        StringBuilder sb = new StringBuilder();
        for (int p : pos)
            // 判断一下,当头为0时,就不用添加;
            if (!(sb.length() == 0 && p == 0))
                sb.append(p);
        return sb.length() == 0 ? "0" : sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(multiply("10", "11"));
    }
}

原文地址:https://www.cnblogs.com/neversayno/p/5434690.html