面向对象程序设计《类与对象、运算符重载》实现大整数类加法

减法、乘法、(除法)我后期会导上去
加法,模拟就行,用字符串模拟手工计算。

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#define N 105
#define Int BigInteger
using namespace std;

class BigInteger {
protected:
    char a[N];
    int lena;
public:
    BigInteger() {}
    BigInteger(char* s) {
        strcpy(a,s);
        lena = strlen(s);
    }
    BigInteger operator + (BigInteger v) {
        char b[N];
        strcpy(b,v.a);
        int lenb = v.lena;
        char ans[N];
        int u = 0, i = lena-1, j = lenb-1, carry = 0;
        while(i >= 0 && j >= 0) {
            int tmp = (a[i]-'0') + (b[j]-'0') + carry;
            if(tmp >= 10) {
                tmp = tmp % 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ans[u++] = '0' + tmp;
            i--, j--;
        }
        while(i >= 0) {
            int tmp = (a[i]-'0') + carry;
            if(tmp >= 10) {
                tmp = tmp % 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ans[u++] = '0' + tmp;
            i--;
        }
        while(j >= 0) {
            int tmp = (b[j]-'0') + carry;
            if(tmp >= 10) {
                tmp = tmp % 10;
                carry = 1;
            } else {
                carry = 0;
            }
            ans[u++] = '0' + tmp;
            j--;
        }
        if(carry == 1) {
            ans[u++] = '1';
        }
        reverse(ans,ans+u);
        ans[u++] = '\0';
        return BigInteger(ans);
    }
    friend ostream& operator << (ostream& out,BigInteger& t);
    friend istream& operator >> (istream& in,BigInteger& t);
};

ostream& operator << (ostream& out,BigInteger& t) {
    out << t.a;
    return out;
}

istream& operator >> (istream& in,BigInteger& t) {
    in >> t.a;
    t.lena = strlen(t.a);
    return in;
}

int main() {
    Int a;
    Int b;
    cin >> a;
    cin >> b;
    Int c = a+b;
    cout << c << endl;
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值