LeetCode 43. Multiply Strings
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
Answer:
1.错位相加,只设一个carryBit的变量记录每次的进位,不用create extra space:
123 x 456 = 56088:
1:3x6 %= 8, c =1 --> 2: 2x6 + 5x3 +1 %= 8, c = 2 --> 3: 6x1+ 5x2 + 4x3 +2 %= 0, c =3 --> 4: 1x5 + 4 x2 + 3 %= 6, c = 1 --> 5: 4x1 + 1 = 5
1 public String multiply(String num1, String num2) { 2 if(num1.length() == 0 || num2.length() ==0) 3 return ""; 4 if(num1.equals("0") || num2.equals("0")) 5 return "0"; 6 int carryBit = 0; 7 String longStr = (num1.length() >= num2.length()) ? num1:num2; 8 String shortStr = (num1.length() < num2.length()) ? num1:num2; 9 String result = ""; 10 int i = 0; 11 int j =0; 12 while(i < longStr.length() && j < shortStr.length()){ 13 int sum = carryBit; 14 int n = j; 15 while(n < shortStr.length()){ 16 if(longStr.length()-1-i+n-j < longStr.length()) 17 sum += (shortStr.charAt(shortStr.length()-1-n)- '0') * (longStr.charAt(longStr.length()-1-i+n-j)- '0'); 18 n++; 19 } 20 carryBit = sum /10; 21 int digit = sum %10; 22 result = digit + result; 23 if(i == longStr.length()-1 ) 24 j++; 25 if(i < longStr.length() -1) 26 i++; 27 } 28 if(carryBit > 0){ 29 result = carryBit + result; 30 } 31 return result; 32 }
2. 输入的两个数和返回的数都是以字符串格式储存的,这样做的原因可能是这样可以计算超大数相乘,可以不受int或long的数值范围的约束,那么我们该如何来计算乘法呢,我们小时候都学过多位数的乘法过程,都是每位相乘然后错位相加,那么这里就是用到这种方法,参见网友JustDoIt的博客,把错位相加后的结果保存到一个一维数组中,然后分别每位上算进位,最后每个数字都变成一位,然后要做的是去除掉首位0,最后把每位上的数字按顺序保存到结果中即可。
c++:
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 string res; 5 int n1 = num1.size(), n2 = num2.size(); 6 int k = n1 + n2 - 2, carry = 0; 7 vector<int> v(n1 + n2, 0); 8 for (int i = 0; i < n1; ++i) { 9 for (int j = 0; j < n2; ++j) { 10 v[k - i - j] += (num1[i] - '0') * (num2[j] - '0'); 11 } 12 } 13 for (int i = 0; i < n1 + n2; ++i) { 14 v[i] += carry; 15 carry = v[i] / 10; 16 v[i] %= 10; 17 } 18 int i = n1 + n2 - 1; 19 while (v[i] == 0) --i; 20 if (i < 0) return "0"; 21 while (i >= 0) res.push_back(v[i--] + '0'); 22 return res; 23 } 24 }