高精度加法器
Add.h
#include <string>
#include <iostream>
#pragma once
#ifndef ADD_H_
#define ADD_H_
// 高精度加法
class Add
{
private:
int* data; // 数据, 从低位到高位排序
int len;
public:
Add() { data = nullptr; len = 0; }
Add(const char* s);
Add(const std::string& s);
Add(const Add& a);
Add& operator= (const Add& a);
~Add();
friend Add operator+(const Add& A, const Add& B);
friend Add& operator+=(Add& A, const Add& B);
friend std::ostream& operator<<(std::ostream& os, const Add& B);
friend std::istream& operator>>(std::istream& ins, Add& B);
explicit operator std::string ();
};
#endif // !ADD_H_
Add.cpp
#include <iostream>
#include <cstring>
#include "Add.h"
using namespace std;
// 高精度加法
Add::Add(const char* s)
{
len = strlen(s);
data = new int[len];
int i = 0;
for (; i < len; i++)
{
data[i] = s[len - 1 - i] - '0';
}
}
Add::Add(const std::string& s)
{
len = s.length();
data = new int[len];
int i = 0;
for (; i < len; i++)
{
data[i] = s[len - 1 - i] - '0';
}
}
Add::Add(const Add& a)
{
len = a.len;
data = new int[len];
int i = 0;
for (; i < len; i++)
{
data[i] = a.data[i];
}
}
Add& Add::operator= (const Add& a)
{
len = a.len;
data = new int[len];
int i = 0;
for (; i < len; i++)
{
data[i] = a.data[i];
}
return *this;
}
Add::~Add()
{
delete[] data;
}
Add operator+(const Add& A, const Add& B)
{
const Add* AB[2];
if (A.len > B.len)
{
AB[0] = &A;
AB[1] = &B;
}
else
{
AB[0] = &B;
AB[1] = &A;
}
int* newnN = new int[AB[0]->len + 1];
int i, tmp = 0;;
for (i = 0; i < AB[1]->len; i++)
{
newnN[i] = tmp + AB[0]->data[i] + AB[1]->data[i];
tmp = newnN[i] / 10;
newnN[i] -= tmp * 10;
}
for (; i < AB[0]->len; i++)
{
newnN[i] = tmp + AB[0]->data[i];
tmp = newnN[i] / 10;
newnN[i] -= tmp * 10;
}
Add C;
if (tmp == 1)
{
newnN[i] == tmp;
C.data = newnN;
C.len = AB[0]->len + 1;
}
else
{
C.data = newnN;
C.len = AB[0]->len;
}
return C;
}
Add& operator+=(Add& A, const Add& B)
{
A = A + B;
return A;
}
std::ostream& operator<<(std::ostream& os, const Add& B)
{
os << "\"";
for (int i = 0; i < B.len; i++)
{
os << B.data[B.len - 1 - i] ;
}
os << "\"";
return os;
}
std::istream& operator>>(std::istream& ins, Add& B)
{
string s;
ins >> s;
B = s;
return ins;
}
Add::operator std::string()
{
string s;
for (int i = 0; i < len; i++)
{
s += data[len - 1 - i] + '0';
}
return s;
}
Text.cpp
#include <iostream>
#include "Add.h"
using namespace std;
int main(void)
{
Add a, b, c;
cin >> a >> b;
cout << a << endl
<< b << endl;
c = a += b;
cout << a << endl
<< b << endl
<< c << endl;
string d = (string)c;
cout << d << endl;
}
测试结果
123456789123456789123456789
12345678987654321
"123456789123456789123456789"
"12345678987654321"
"123456789135802468111111110"
"12345678987654321"
"123456789135802468111111110"
123456789135802468111111110