1. 程式人生 > >leetcode multiply-strings

leetcode multiply-strings

-- multi ive lib 開始 ring repr number 會有

題幹:

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 integerdirectly.

大意:

  大整數乘法

輸入:string

輸出:string

思路:

  1、計算乘積中對應位的結果。不考慮進位時,根據乘數位數可以確定乘積位數,乘積對應位置的數是由乘數確定位置的數確定。如num1*num2,結果會有len1-1+len2-1+1位。計算時:

R[len - i - j]+=((num1[i]-‘0‘)*(num2[j]-‘0‘));

 

  2、處理進位。乘積計算完後將進位由低位開始向高位進位調整每位符合十進制數

  3、去掉前導零。

class Solution {
public:
    string multiply(string num1, string num2) {
        int len1=num1.length(),len2=num2.length();
        int len = len1+len2-2;
        int C = 0;
        int R[220]={0};
        
string ans;//對應位乘 for(int i = 0 ; i < len1;i++){ for(int j = 0;j < len2;j++){ R[len - i - j]+=((num1[i]-0)*(num2[j]-0)); } } //處理進位 for(int i = 0 ; i < len1+len2 ;i++){ R[i] += C; C = R[i]/10; R[i] %= 10; } //處理前導0 int k = len1+len2; while(!R[k]){ k--; if(k<0) return "0"; } //壓入string返回 for(int i = k ; i >= 0;i--){ ans.push_back(R[i]+0); } return ans; } };

leetcode multiply-strings