Big Integer multiplication

http://www.lintcode.com/en/problem/big-integer-multiplication/?rand=true

public class Solution {
    /*
     * @param num1: a non-negative integers
     * @param num2: a non-negative integers
     * @return: return product of num1 and num2
     */
    public String multiply(String num1, String num2) {
        // write your code here
        int[] res = new int[num1.length() + num2.length()];
        char[] chars2 = num2.toCharArray();
        char[] chars1 = num1.toCharArray();
        int index = 0;
        for (int i = chars2.length - 1; i >= 0; i--) {
            int a = chars2[i] - '0';
            for (int j = chars1.length - 1; j >= 0; j--) {
                int b = chars1[j] - '0';
                b *= a;
                int tempIndex = res.length - 1 - (chars2.length - 1 - i) - (chars1.length - 1 - j);
                res[tempIndex] += b;
                if (res[tempIndex] >= 10) {
                    res[tempIndex - 1] += res[tempIndex] / 10;
                    res[tempIndex] %= 10;
                }
                index = tempIndex;
            }
        }
        index--;
        while (res[index] >= 10) {
            res[index - 1] += res[index] / 10;
            res[index] %= 10;
            index--;
        }
        while (res[index] == 0) {
            index++;
            if (index >= res.length) {
                return "0";
            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = index; i < res.length; i++) {
            sb.append(res[i]);
        }
        return sb.toString();
    }
}

你可能感兴趣的:(Big Integer multiplication)