Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
public String multiply(String num1, String num2) {
        if (num1.equals("0")||num2.equals("0")){
            return "0";
        }
        int[] n1 = new int[num1.length()];
        int[] n2 = new int[num2.length()];

        for (int i = 0; i < n1.length; i++) {
            n1[i] = num1.charAt(num1.length()-1-i)-'0';
        }
        for (int i = 0; i < n2.length; i++) {
            n2[i] = num2.charAt(num2.length()-1-i)-'0';
        }

        int[] result = new int[n1.length+n2.length];
        for (int i = 0; i < n1.length; i++) {
            for (int j = 0; j < n2.length; j++) {
                result[i+j]+=n1[i]*n2[j];
            }
        }

        for (int i = 0; i < result.length-1; i++) {
            result[i+1] += result[i]/10;
            result[i] %= 10;
        }

        String result1 = "";

        for (int i = result.length-1 ; i >=0 ; i--) {

            result1+=result[i];
        }
        return result1.replaceFirst("^0*","");
    }
posted @ 2018-03-05 16:03  binryang  阅读(77)  评论(0)    收藏  举报