Sunday, August 30, 2015

Leetcode: Multiply Strings (string)

PROBLEM:

https://leetcode.com/problems/multiply-strings/

--------------------------------------------------

The shorter one is set as multiplicand and then using the normal multiplication process shown above. To easily deal with the alingment in summation, reverse the multiplication results. In the end reverse the summation result. 

///////////////////////////////////////////////////////////////
//
class Solution {
public:
       string multiply(string num1, string num2) {
              vector<vector<int>> dig;
              int n1 = num1.size(), n2 = num2.size();
              string lg, sht;
              int iLong, iShort;
              //choose short one as multiplicand
              if (n1<n2){
                     lg = num2; sht = num1;
                     iLong = n2; iShort = n1;
              }
              else{
                     lg = num1; sht = num2;
                     iLong = n1; iShort = n2;
              }

              int count = 0;
              for (int i = iShort - 1; i>-1; i--){
                     int a = sht[i] - '0', c = 0;
                     vector<int> tmp;
                     tmp.resize(count, 0);
                     for (int j = iLong - 1; j>-1; j--){
                           int b = (lg[j] - '0')*a + c, rem = b % 10;
                           c = b / 10;
                           tmp.push_back(rem);
                     }
                     tmp.push_back(c);
                     tmp.resize(iLong + iShort, 0);//resize to the same length
                     dig.push_back(tmp);

                     count++;
              }

              //do summation
              vector<int> tmp1;
              unsigned long long c1 = 0, sum = 0;
              for (int k = 0; k<iLong + iShort; k++){
                     for (int m = 0; m<iShort; m++){
                           sum = sum + dig[m][k];
                     }
                     sum += c1;
                     int res = sum % 10;
                     tmp1.push_back(res);
                     c1 = sum / 10;
                     sum = 0;
              }
              // push back the c1
              while (c1>0){
                     tmp1.push_back(c1 % 10);
                     c1 = c1 / 10;
              }
              //restore the final string
              int l = iLong + iShort - 1;
              while (tmp1[l] == 0)l--;//
              string result;
              for (; l>-1; l--){
                     result.push_back(tmp1[l] + '0');
              }
              if (result.size() == 0) return "0";
              return result;
       }
};

No comments:

Post a Comment