LeetCode-------43. Multiply Strings(字符串的乘法运算)

来源:互联网 发布:thnkphp pdo 新增数据 编辑:程序博客网 时间:2024/06/05 14:55

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.

Subscribe to see which companies asked this question

public class Solution {    public String multiply(String num1, String num2) {        if (num1 == null || num2 == null) {            return null;        }                int len1 = num1.length(), len2 = num2.length();        int len3 = len1 + len2;        int i, j, product, carry;        int[] num3 = new int[len3];        for (i = len1 - 1; i >= 0; i--) {            carry = 0;            for (j = len2 - 1; j >= 0; j--) {                product = carry + num3[i + j + 1] +                    Character.getNumericValue(num1.charAt(i)) *                    Character.getNumericValue(num2.charAt(j));                num3[i + j + 1] = product % 10;                carry = product / 10;            }            num3[i + j + 1] = carry;        }        StringBuilder sb = new StringBuilder();        i = 0;        while (i < len3 - 1 && num3[i] == 0) {            i++;        }        while (i < len3) {            sb.append(num3[i++]);        }        return sb.toString();    }}


0 0