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:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
my code:
class Solution { public: string multiply(string num1, string num2) { int len1 = num1.length(); int len2 = num2.length(); if (len1 == 1 && num1[0] == '0' || len2 == 1 && num2[0] == '0') return "0"; vector<string> v; int incidental; int multiply; for (int i = len2 - 1; i >= 0; --i) { incidental = 0; int n2 = num2[i] - '0'; string tem = ""; for (int k = (len2 - 1) - i; k > 0; --k) { tem += '0'; } for (int j = len1 - 1; j >= 0; --j) { int n1 = num1[j] - '0'; multiply = n1 * n2 + incidental; incidental = multiply / 10; tem += to_string(multiply%10); } if (incidental != 0) tem += to_string(incidental); v.push_back(tem); } int max_length = v.back().size(); string ans = ""; int flag; incidental = 0; for (int i = 0; i < max_length; ++i) { flag = 0; for (int j = 0; j < v.size(); ++j) { if (i < v[j].size()) { int tage = v[j][i] - '0'; flag += tage; } } flag += incidental; incidental = flag / 10; ans = to_string(flag % 10) + ans; } if (incidental != 0) ans = to_string(incidental) + ans; return ans; } };
Runtime: 24 ms, faster than 14.44% of C++ online submissions for Multiply Strings.
efficient code:
class Solution { public: string multiply(string num1, string num2) { string sum(num1.size() + num2.size(), '0'); for (int i = num1.size() - 1; 0 <= i; --i) { int carry = 0; for (int j = num2.size() - 1; 0 <= j; --j) { int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry; sum[i + j + 1] = tmp % 10 + '0'; carry = tmp / 10; } sum[i] += carry; } size_t startpos = sum.find_first_not_of("0"); if (string::npos != startpos) { return sum.substr(startpos); } return "0"; } };
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Multiply Strings.