LeetCode 43. Multiply Strings
原题链接在这里:https://leetcode.com/problems/multiply-strings/
题目:
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:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
题解:
Method 1:通过这道题, 学到了BigInteger的用法, 他的constructor 可以直接从string建立BigInteger, 但要注意它的乘法API是bi1.multiply(bi2).
若是中间需要考虑溢出,还有bi1.intValue(), bi1.longValue()等API.
Method 2:若num1.length() = m, num2.length() = n, 那么结果的长度为m+n-1(没有进位),或者是m+n(有进位)。
以289*758为例:
生成数组d来储存成绩和结果,例子中的14,66,119,109,72行,然后取余进位.
为了方便起见,把原string reverse.
Note: corner case "0" * "1234", if either string starts with 0, return "0". Otherwise it would return "0000".
Time Complexity: O(len1*len2).
Space: O(len1+len2).
AC Java:
1 import java.math.*; 2 public class Solution { 3 public String multiply(String num1, String num2) { 4 /*Method 1 5 if(num1 == null || num2 == null || num1.length() ==0 || num2.length() == 0) 6 return ""; 7 BigInteger bi1 = new BigInteger(num1); 8 BigInteger bi2 = new BigInteger(num2); 9 10 BigInteger res = bi1.multiply(bi2); 11 return res.toString(); 12 */ 13 14 //Method 2 15 if(num1 == null || num1.length() == 0 || num2 == null || num2.length() == 0){ 16 return ""; 17 } 18 if(num1.charAt(0) == '0' || num2.charAt(0) == '0'){ 19 return "0"; 20 } 21 num1 = new StringBuilder(num1).reverse().toString(); 22 num2 = new StringBuilder(num2).reverse().toString(); 23 int len1 = num1.length(); 24 int len2 = num2.length(); 25 26 int [] d = new int[len1 + len2]; 27 for(int i = 0; i<len1; i++){ 28 int a = num1.charAt(i) - '0'; 29 for(int j = 0; j<len2; j++){ 30 d[i+j] += a * (num2.charAt(j)-'0'); 31 } 32 } 33 34 int cur = 0; 35 int carry = 0; 36 StringBuilder sb = new StringBuilder(); 37 for(int i = 0; i<d.length; i++){ 38 cur = (d[i]+carry)%10; 39 carry = (d[i]+carry)/10; 40 sb.insert(0,cur); 41 } 42 if(sb.charAt(0) == '0'){ 43 sb.deleteCharAt(0); 44 } 45 return sb.toString(); 46 } 47 }
类似Add Strings.