1. 大数相减
首先判断符号,然后再计算大小
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string Sub(string , string );
string sub(string a, string b)
{
// 1. judge who is biger
bool firstBig = false;
if (a.size() > b.size())
{
firstBig = true;
}
else if (a.size() == b.size())
{
int i = 0;
while (i < a.size() && a[i] == b[i])
i++;
if (i == a.size() || a[i] == b[i]) return string(1,'0');
if (a[i] > b[i]) firstBig = true;
}
// 2. get the output
string c;
if (firstBig == true)
return Sub(a, b);
else
return '-' + Sub(b, a);
}
string Sub(string a, string b)
{
int dec = 0;
int m = a.size() - 1;
int n = b.size() - 1;
string c(a.size(), '0');
while (m >= 0 && n >= 0)
{
int temp = a[m] - b[n] - dec;
if (temp < 0)
{
dec = 1;
temp += 10;
}
c[m] = temp + '0';
m--;
n--;
}
while (m >= 0)
{
int temp = a[m] - dec - '0';
if (temp < 0)
{
dec = 1;
temp += 10;
}
c[m] = temp + '0';
m--;
}
m = 0;
while (c[m] == '0')
{
m++;
}
return c.substr(m, c.size() - m);
}
int main()
{
string a, b;
while (cin >> a >> b)
{
cout << sub(a, b) <<endl;
}
return 0;
}
2. 大数相乘
与手算乘法的流程一致,首先计算有多少个1,多少个10,多少个100,最后再重新统计表示
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
string muti(string a, string b)
{
if (a.size() == 0 || b.size() == 0 || a == "0" || b == "0") return "0";
vector<int> ret(a.size() + b.size(),0);
int base = a.size() + b.size() - 2;
for (int i = b.size() - 1; i >= 0; i--)
{
for (int j = a.size() - 1; j >= 0; j--)
{
ret[base - i - j] += (a[j] - '0') * (b[i] - '0');
}
}
int carry = 0;
for (int i = 0; i < ret.size(); i++)
{
int tmpcarry = (ret[i] + carry) / 10;
ret[i] = (ret[i] + carry) % 10;
carry = tmpcarry;
}
while (carry > 0)
{
ret.push_back(carry%10);
carry = carry / 10;
}
int i = ret.size() - 1;
while (ret[i] == 0)
i--;
string c(i+1, '0');
for (int j = 0; i >= 0; i--)
{
c[i] = ret[j++] + '0';
}
return c;
}
int main()
{
string a, b;
while (cin >> a >> b)
{
cout << muti(a, b) <<endl;
}
return 0;
}