大整数加法

大整数加法

// 大整数加法
//
#include "stdafx.h"
#include<stdio.h>
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class bigInteger {
public:
    int digit[1000];
    int size;
    bigInteger();
    void init();
    void set(string);
    bigInteger operator+(const bigInteger &A)const;
    void display();
};

bigInteger::bigInteger() {
    for (int i = 0; i < 1000; i++) digit[i] = 0;
    size = 0;
}

void bigInteger::init() {
    for (int i = 0; i < 1000; i++)digit[i] = 0;
    size = 0;
}

void bigInteger::set(string str) {
    int strLen = str.length();
    for (int i = strLen - 1, t = 0, c = 1; i >= 0; i--) {
        t += (str[i] - '0')*c;
        c *= 10;
        if (c == 10000 || i == 0) {//c==10000代表每个digit[i]存储四位数
            digit[size++] = t;
            t = 0; c = 1;
        }
    }
}

bigInteger bigInteger::operator+ (const bigInteger &A)const {
    bigInteger ret;
    int carry = 0;
    for (int i = 0; i < A.size || i < size; i++) {
        ret.digit[ret.size++] = (A.digit[i] + digit[i] + carry) % 10000;
        carry = (A.digit[i] + digit[i] + carry) / 10000;
    }
    if (carry != 0)ret.digit[ret.size++] = carry;
    return ret;
}

void bigInteger::display() {
    for (int i = size - 1; i >= 0; i--) {
        if (i == (size - 1))cout << digit[i];
        else cout << setw(4) << setfill('0') << digit[i];
    }
    if (size == 0)cout << "0";
    cout << endl;
}

int main()
{
    bigInteger a, b, c;
    string str1, str2;
    while (cin >> str1 >> str2) {
        c.init();
        a.init();
        b.init();
        a.set(str1);
        b.set(str2);
        c = a + b;
        c.display();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值