参考 http://www.cnblogs.com/studynote/p/3445398.html
#include <iostream>
#include <time.h>
using namespace std;
class BigInt {
public:
//BigInt();
BigInt(const char*);
BigInt(unsigned int n = 0);
BigInt(const BigInt&);
BigInt& operator=(const BigInt&);
BigInt operator + (const BigInt& other) const;
void print(FILE* F = stdout) const;
~BigInt() {
delete[] digits;
}
private:
char* digits;
unsigned ndigits;
BigInt(char* d, unsigned n) {
digits = d;
ndigits = n;
}
friend class DigitStream;
};
void BigInt::print(FILE *f) const {
for (int i = ndigits - 1; i >= 0; --i) {
fprintf(f, "%c", digits[i] + '0');
}
}
BigInt::BigInt(const BigInt& n) {
unsigned i = n.ndigits;
digits = new char[i];
ndigits = i;
memcpy(digits, n.digits, i);
}
BigInt& BigInt::operator=(const BigInt& n) {
if (this != &n) {
BigInt tmp(n);
swap(tmp.ndigits, ndigits);
swap(tmp.digits, digits);
}
return *this;
}
BigInt::BigInt(unsigned n) {
char d[3 * sizeof(unsigned) + 1];
char *dp = d;
ndigits = 0;
do {
*dp++ = n % 10;
n /= 10;
ndigits++;
} while (n > 0);
digits = new char[ndigits];
for (register int i = 0; i < ndigits; ++i) {
digits[i] = d[i];
}
}
BigInt::BigInt(const char* digitString) {
size_t n = strlen(digitString);
if (n != 0) {
ndigits = n;
digits = new char[n];
for (int i = 0; i < n; ++i) {
digits[i] = digitString[n - 1 - i] - '0';
}
}
else {
ndigits = 1;
digits = new char[ndigits];
digits[0] = 0;
}
}
BigInt BigInt::operator+(const BigInt& n) const {
size_t maxDigits = max(ndigits, n.ndigits) + 1;
char carry = 0;
char* sumPtr = new char[maxDigits];
BigInt sum(sumPtr, maxDigits);
for (int i = 0; i < max(ndigits, n.ndigits); ++i) {
*sumPtr = carry;
if (i < ndigits) {
char tmp = digits[i];
*sumPtr += digits[i];
tmp = *sumPtr;
int a = 0;
}
if (i < n.ndigits) {
char tmp = digits[i];
*sumPtr += n.digits[i];
tmp = *sumPtr;
int a = 0;
}
if (*sumPtr >= 10) {
carry = 1;
*sumPtr -= 10;
}
else {
carry = 0;
}
++sumPtr;
}
if (carry > 0) {
*sumPtr = carry;
}
else {
sum.ndigits = max(ndigits, n.ndigits);
}
return sum;
}
void test() {
clock_t start = clock();
BigInt b(10);
for (int i = 1; i <= 1; ++i) {
b = b + 1;
}
b.print();
clock_t end = clock();
cout << endl << static_cast<double>(end - start) / CLOCKS_PER_SEC << endl;
}
int main(int argc, _TCHAR* argv[])
{
test();
_CrtDumpMemoryLeaks();
cin.get();
return 0;
}