上次写了一个“无符号大整数加法”,是比较容易的,这次实现了完整的大整数的加减法,支持有符号的!不过实现起来感觉不是很顺畅,感觉可以优化的地方还很多,先贴一下代码,日后再来优化。
另,思路主要是模拟手算的过程,计算方式在注释里有说清楚。
// BigInteger.h
#ifndef __BIG_INTEGER__H__
#define __BIG_INTEGER__H__
#include <string>
using namespace std;
class BigInteger {
public:
BigInteger(string str);
BigInteger add(const BigInteger& other);
BigInteger sub(const BigInteger& other);
friend ostream& operator << (ostream& out, BigInteger& num);
private:
string m_data;
bool m_isNeg;
private:
static void align(string& str, int len);
static bool strip(string& str);
static bool isOKChar(char ch);
static BigInteger addAbsoluteValue(const BigInteger& A, const BigInteger& B);
static BigInteger subAbsoluteValue(const BigInteger& A, const BigInteger& B);
static int compareAbsoluteValue(const BigInteger& A, const BigInteger& B);
};
#endif
// BigInteger.cpp
#include "BigInteger.h"
#include <assert.h>
#include <iostream>
using namespace std;
// 使一个表示数字的字符串对齐到len的长度,方便后续位对位的运算
void BigInteger::align(string& str, int len) {
if (len > str.size())
str.insert(0, len - str.size(), '