程序媛詹妮弗
终身学习

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.

 

题意:

高精度乘法。

 

Solution1: Math 

Do the simulation like how computer will do multiplication operation

1一个char对应1个digit, 

digit相乘后,注意其乘积结果可能需要进位

 

code

 1 /*
 2 Time: O(n^2). We use nested 2 for loop
 3 Space: O(n). We use int[] to save intermedia infor
 4 */
 5 
 6 class Solution {
 7     public String multiply(String num1, String num2) {
 8         if(num1.length()==0 || num2.length()==0) return "0";
 9         int len1 = num1.length();
10         int len2 = num2.length();
11         int [] result = new int [len1+len2];
12         
13         for(int i = len1-1; i>=0; i--){
14             for(int j = len2-1; j>=0;j--){
15                 int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
16                 int idx = i+j+1;
17                 // 可能会进位
18                 int carryIdx = i+j;
19                 mul = mul + result[idx];
20                 result[idx] = mul % 10;
21                 result[carryIdx] = result[carryIdx] + mul/10;
22             }
23         }
24         StringBuilder sb = new StringBuilder();
25         for(int res: result){
26             if(sb.length()!=0 || res!=0) sb.append(res);
27         } 
28         return (sb.length() == 0)? "0" : sb.toString();     
29     }
30 }

 

posted on 2019-04-15 03:09  程序媛詹妮弗  阅读(153)  评论(0编辑  收藏  举报