题目:
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.
题解:其实就是考察乘法运算,我采用的方法是不同位之间相乘,属于同一位的相乘结果则相加,如果有下面的进位,则再加进位。例如,123*123,第一个数的2属于第二位,第二个数的3属于第一位,所以他们相乘的结果属于第二位,同理,第一个的3属于第一位,第二个的2属于第二位,他们相乘的结果属于第二位,这样,属于相同位数的数字相加,再加上低位的进位,最后就可以得到总的位数。
代码中的数组是从0开始的,所以,注意一下下标,还有,代码中有很多魔数= = ,代码风格还是不好哪。。。。
class Solution {
public:
string multiply(const string &num1,const string &num2) {
if(num1=="0" || num2=="0") return "0";
int length1 = num1.length();
int length2 = num2.length();
int* n1 = new int[length1];
int* n2 = new int[length2];
int* result = new int[length1+length2-1];
memset(result, 0, sizeof(int)*(length1+length2-1));
for (int i=0; i<length1; i++)
{
n1[i] = num1[length1-i-1]-'0';
}
for (int i=0; i<length2; i++)
{
n2[i] = num2[length2-i-1]-'0';
}
for (int i=0; i<length1; i++)
for (int j=0; j<length2; j++)
{
result[i+j] += n1[i]*n2[j];
}
int index=0;
for (int i=0; i<length1+length2-1; i++)
{
int answer = index + result[i];
index = answer/10;
result[i]=answer%10;
}
string s="";
for (int i=0; i<length1+length2-1; i++)
{
char a = result[i]+'0';
s = a + s;
}
if (index != 0){
char b = index + '0';
s = b + s;
}
return s;
}
};