1. 程式人生 > >Multiply Strings

Multiply Strings

es2017 question rep 字符 placed break 一個數 rip spa

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.

技術分享

  基本思路:如上圖所示,因為兩個字符串相乘,長度不定,可以將結果存到一個數組中。我們可以看到num1[i]和num2[j]的乘積最後位置是在indices[i+j]和indices[i+j+1]兩個位置上,同時我們知道

一個m位的數乘一個n位的數做多是m+n位。

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {//num1[i] * num2[j]` will be placed         
 4                                                //
at indices `[i + j`, `i + j + 1]` m*n位數最多m+n位 5 string result; 6 int k = 0, sum = 0; 7 int len1 = num1.size(), len2 = num2.size(); 8 vector<int> res(len1 + len2); 9 for (int i = len1-1; i>=0;i--) 10 { 11 for (int j = len2-1; j >= 0
; j--) 12 { 13 int k = (num1[i] - 0)*(num2[j]-0); 14 sum = k + res[i + j + 1];//前一次最高位 15 res[i + j + 1] = sum % 10; 16 res[i + j] += sum / 10; 17 } 18 } 19 //去除首位的0 20 int j = len1 + len2 - 1; 21 for (int i = 0; i <len1+len2; i++) 22 { 23 if (res[i] == 0) continue; 24 else 25 { 26 j = i; 27 break; 28 } 29 } 30 for (int i = j; i < len1 + len2; i++) 31 { 32 result += res[i] + 0; 33 } 34 return result; 35 } 36 };

Multiply Strings