class Solution {
//draw it out and then observe it to find out the regular pattern
//more practice is needed
public:
string multiply(string num1, string num2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(num1.size() == 0 || num2.size() == 0) return string("");
string ans(num1.size()+num2.size()+1, '0');//important observation
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
for (int digIdx2 = 0; digIdx2 < num2.size(); ++digIdx2)//the below number num2
{
int dig2 = num2[digIdx2]-'0';
int carry = 0;
for (int digIdx1 = 0; digIdx1 < num1.size(); ++digIdx1)//the up number num1
{
int dig1 = num1[digIdx1]-'0';
int tmp = ans[digIdx1+digIdx2]-'0';
int sum_cur = carry+dig1*dig2+tmp;
ans[digIdx1+digIdx2] = sum_cur%10+'0';
carry = sum_cur/10;
}
ans[digIdx2+num1.size()] = carry+'0';
}
reverse(ans.begin(), ans.end());
int posStart = ans.find_first_not_of('0');
if(posStart < 0 || posStart >= ans.size()) //in case of ""000"
posStart = ans.size()-1;
int len = ans.size()-posStart;
return ans.substr(posStart, len);
}
};
second time
class Solution {
public:
string multiply(string num1, string num2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
int carry = 0;
string result;
for(int len = 0; ;++len)
{
int sum = 0;
bool flag = false;
for(int i = 0; i < num1.size(); ++i)
{
int j = len-i;
if(j < 0 || j >= num2.size()) continue;
sum += (num1[i]-'0')*(num2[j]-'0');
flag = true;
}
if(!flag) break;
sum += carry;
result.push_back(sum%10+'0');
carry = sum/10;
}
while(carry > 0)
{
result.push_back(carry%10+'0');
carry /= 10;
}
reverse(result.begin(), result.end());
if(result.find_first_not_of('0') == string::npos) return "0";
else return result.substr(result.find_first_not_of('0'), result.size()-result.find_first_not_of('0'));
}
};