Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Subscribe to see which companies asked this question
思路分析:
乘法原理,感觉如果用数组来计算会简单很多,用字符串必须再每次循环后处理一下高位的进位问题,比较麻烦。
1、当个位数相乘时,digit无用。
即当123 x 54 时,当 4 x 123 digit 始终为0,此后 digit位表示每一位的进位值。
/*
*/
#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;
class Solution_043_MultiplyStringsArray
{
public:
string multiply(string num1, string num2)
{
// Start typing your C/C++ solution below
// DO NOT write int main() function
string s(num1.size() + num2.size(), '0');
reverse(num1.begin(), num1.end());
reverse(num2.begin(), num2.end());
for (int i = 0; i < num1.size(); i++)
{
int flag = 0;
for (int j = 0; j < num2.size(); j++)
{
int digit = s[i + j] - '0';
int num = (num1[i] - '0') * (num2[j] - '0');
int res = digit + num + flag;
s[i + j] = (res % 10) + '0';
flag = res / 10;//进位
}
int index = i + num2.size();
while (flag)
{
int digit = s[index] - '0';
int res = digit + flag;
s[index] = (res % 10) + '0';
flag = res / 10;
}
}
while (true)
{
if (s[s.size() - 1] == '0' && s.size() > 1)
s.erase(s.size() - 1, 1);
else
break;
}
reverse(s.begin(), s.end());
return s;
}
};