标签:
Notes:
1. Dont have to allocate l1*l2, just l1+l2 is fare enough.
2. remember i--, j--.
3. upgrade[i+j] is += not = rec[i+j+1]/10;
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 int l1 = num1.size(), l2 = num2.size(); 5 if (l1 == 0 || l2 == 0 || num1 == "0" || num2 == "0") return "0"; 6 vector<int> rec(l1+l2, 0); 7 unordered_map<int, int> upgrade; 8 string result; 9 for (int i = l1-1; i >= 0; i--) { 10 for (int j = l2-1; j >=0; j--) { 11 rec[i+j+1] += int(num1[i] - ‘0‘) * int(num2[j] - ‘0‘); 12 rec[i+j+1] += upgrade[i+j+1]; 13 upgrade[i+j+1] = 0; 14 upgrade[i+j] += rec[i+j+1]/10; 15 rec[i+j+1] %= 10; 16 if (i == 0 && j == 0 && upgrade[0]) rec[0] = upgrade[0]; 17 } 18 } 19 bool flag = true; 20 for (int i = 0; i < l1+l2; i++) { 21 if (flag && rec[i] == 0) continue; 22 else flag = false; 23 result += char(rec[i] + ‘0‘); 24 } 25 return result; 26 } 27 };
LeetCode – Refresh – Multiply Strings
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/4355144.html