大数字的加减乘法实现
程序员文章站
2022-06-08 23:42:20
...
两个数字的加减乘法,当数字大小超过了计算机内置类型所允许的范围,用字符串模拟加减乘法的过程来实现大数字的加减乘法,除法比较复杂,日后再补充;
加法:
string aplus(string a, string b)
{
string res;
int i = a.length() - 1, j = b.length() - 1, t1, t2, sum = 0;
bool sta = false; //进位标记,有进位为true
for (; i >= 0 && j >= 0; i--, j--)
{
t1 = a[i] - '0';
t2 = b[j] - '0';
sum = t1 + t2;
if (sta == true)
{
sum ++;
sta = false;
}
if (sum >= 10)
{
sum = sum - 10;
sta = true;
}
char ch = sum + '0';
res = ch + res;
}
for (; i >= 0; i--)
{
sum = a[i] - '0';
if (sta == true)
{
sum++;
sta = false;
}
if (sum >= 10)
{
sum = sum - 10;
sta = true;
}
char ch = sum + '0';
res = ch + res;
}
for (; j >= 0; j--)
{
sum = b[j] - '0';
if (sta == true)
{
sum++;
sta = false;
}
if (sum >= 10)
{
sum = sum - 10;
sta = true;
}
char ch = sum + '0';
res = ch + res;
}
if (sta == true)
res = '1' + res;
return res;
}
乘法:被乘数的每一位去乘以乘数,再将和按照乘法的规律相加,得到积;
string amulti(string a, string b)
{
vector<string> data;
bool sta = false;
string zero;
for (int i = b.length() - 1; i >= 0; i--)
{
string cnt;
int t1 = b[i] - '0';
int tsum = 0, step = 0;
for (int j = a.length() - 1; j >= 0; j--)
{
int t2 = a[j] - '0';
if (sta == true)
{
tsum = t1 * t2 + step;
step = 0;
sta = false;
}
else
tsum = t1*t2;
if (tsum >= 10)
{
step = tsum / 10;
tsum = tsum % 10;
sta = true;
}
char ch = tsum + '0';
cnt = ch + cnt;
}
if (sta == true)
{
char ch = step + '0';
cnt = ch + cnt;
}
cnt = cnt + zero;
data.push_back(cnt);
zero = zero + '0';
}
string res = "0";
for (vector<string>::iterator it = data.begin(); it != data.end(); it++)
res = aplus(res, *it);
return res;
}
减法:
//a和b是大数字,输入时要求且a比b大,sta作为结果正负的判断依据
string sub(string a, string b, bool sta)
{
string res;
int i = a.length() - 1, j = b.length() - 1;
bool stasub = false;
int t1, t2, sum;
for (; i >= 0 && j >= 0; i--, j--)
{
t1 = a[i] - '0';
t2 = b[j] - '0';
if (stasub == true)
{
sum = t1 - t2 - 1;
stasub = false;
}
else
sum = t1 - t2;
if (sum < 0)
{
sum = sum + 10;
stasub = true;
}
char ch = sum + '0';
res = ch + res;
}
for (; i >= 0; i--)
{
sum = a[i] - '0';
if (stasub == true)
{
sum--;
stasub = false;
}
if (sum < 0)
{
sum = sum + 10;
stasub = true;
}
char ch = sum + '0';
res = ch + res;
}
int k = 0;
while (res[k] == '0')
k++;
string out;
for (; k < res.length(); k++)
out = out + res[k];
if (sta == true)
out = '-' + out;
return out;
}
调用过程:
int main()
{
string a, b;
while (cin >> a >> b)
{
cout << aplus(a, b) << endl;
if (a.length() > b.length())
{
cout << sub(a, b, false) << endl;
cout << amulti(a, b) << endl;
}
else if (a.length() < b.length())
{
cout << sub(b, a, true) << endl;
cout << amulti(b, a) << endl;
}
else if (a == b)
{
cout << 0 << endl;
cout << amulti(a, b) << endl;
}
else
{
for (int i = 0; i <a.length(); i++)
{
if (a[i] > b[i])
{
cout << sub(a, b, false) << endl;
break;
}
else if (a[i] < b[i])
{
cout << sub(b, a, true) << endl;
break;
}
else
continue;
}
cout << amulti(a, b) << endl;
}
}
}
下一篇: Python文件读取的3种方法及路径转义