大整数类-实现加减法

本文介绍了如何实现有符号大整数的加减法,通过模拟手动计算过程,详细阐述了计算逻辑,并提供了现有代码,计划后续进行优化。
摘要由CSDN通过智能技术生成

上次写了一个“无符号大整数加法”,是比较容易的,这次实现了完整的大整数的加减法,支持有符号的!不过实现起来感觉不是很顺畅,感觉可以优化的地方还很多,先贴一下代码,日后再来优化。

另,思路主要是模拟手算的过程,计算方式在注释里有说清楚。

// 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(), '
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值