43. Multiply Strings

Problem:
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

7/24/2018 update:

      1 2 3
      4 5 6
-------------------
      7 3 8
      1 5
      p1p2
See above example. We need to sum 738 and 15. p2 store2 the digit of 3*5 + 3. p1 stores the carry from 3*5 + 3 plus prev p1 7.   The temp result is 738 + 150 = 888. The core idea of the solution is calc result step by step. 
--------------------------------------------------------------------------------------------------------------------------------------------
Analysis:
盗个图
rolling two pointers p1 and p2. p1 holds the carry, p2 holds the digit. Current product should add the previous carry digits[p2] (previous p1). 

Solution:

class Solution {
    public String multiply(String num1, String num2) {
        int m = num1.length();
        int n = num2.length();
        int[] digits  = new int[m + n];
        int p1 = 0, p2 = 0;
        for (int i = m - 1; i >= 0; i--)
            for (int j = n - 1; j >= 0; j--) {
                int product = (num1.charAt(i) - '0') *  (num2.charAt(j) - '0');
                p1 = i + j;
                p2 = i + j + 1;
        
                int sum = product + digits[p2];
                digits [p1] += sum/10;
                digits [p2] = sum%10;
            }

        StringBuilder sb = new StringBuilder();
        for (int i: digits ) {
            if (sb.length() == 0 && i == 0) continue;
            sb.append(i);
        }

        return sb.length() == 0? "0" : sb.toString();
    }
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List