众所周知,计算机的整数类型表示的范围是有限的,因此,对于一个很大的数,经常用数组或者字符串去表示。字符串可以看做是字符数组,本质上还是数组表示大数。那么,大数的加法和乘法该怎么计算呢?这里给出简单的算法代码。
class Solution {
public:
string add(string& num1, string& num2)
{
//先比较两个数哪个更长
int len1 = num1.size();
int len2 = num2.size();
int len = len1 > len2 ? len1 : len2;
string res;
int carry = 0;
for (int i = 0; i < len; i++)
{
//将num1和num2从低位开始取出对应位
int a = 0, b = 0;
a = len1 > i ? num1[len1 - i - 1]-'0' : 0;
b = len2 > i ? num2[len2 - i - 1]-'0' : 0;
int temp = a + b + carry;
carry = temp / 10;
res.insert(res.begin(), '0'+temp%10);
}
if (carry)
res.insert(res.begin(), '0' + carry);
return res;
}
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0")
return "0";
int len1 = num1.size();
int len2 = num2.size();
string res;
int carry = 0;
for (int i = 0; i < len1; i++)
{
string temp;
int a = num1[len1 - i - 1] - '0';
for (int j = 0; j < len2; j++)
{
int b = num2[len2 - j - 1] - '0';
int cur = a*b + carry;
carry = cur / 10;
temp.insert(temp.begin(), cur % 10+'0');
}
if (carry)
{
temp.insert(temp.begin(), carry + '0');
carry = 0;
}
for(int k = 0; k < i; k++)
temp.push_back('0');
res = add(temp, res);
}
return res;
}
};