leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0043.cpp (844B)


      1 class Solution {
      2   public:
      3     string multiply(string num1, string num2) {
      4         if (num1 == "0" || num2 == "0") return "0";
      5 
      6         reverse(num1.begin(), num1.end());
      7         reverse(num2.begin(), num2.end());
      8         string answer(num1.size() + num2.size(), '0');
      9 
     10         for (int p2 = 0; p2 < num2.size(); p2++) {
     11             int d2 = num2[p2] - '0';
     12             for (int p1 = 0; p1 < num1.size(); p1++) {
     13                 int d1 = num1[p1] - '0';
     14 
     15                 int numZero = p1 + p2;
     16                 int carry = answer[numZero] - '0';
     17                 int mul = d1 * d2 + carry;
     18                 answer[numZero] = mul % 10 + '0';
     19                 answer[numZero + 1] += mul / 10;
     20             }
     21         }
     22         if (answer.back() == '0') answer.pop_back();
     23 
     24         reverse(answer.begin(), answer.end());
     25         return answer;
     26     }
     27 };