a+b(华中科技大学复试上机题)

a+b(华中科技大学复试上机题)

题目链接
在这里给出大整数其他运算的模板

题目描述

实现一个加法器,使其能够输出a+b的值。

输入描述:

输入包括两个数a和b,其中a和b的位数不超过1000位。

输出描述:

可能有多组测试数据,对于每组数据,
输出a+b的值。

示例1

输入

2 6
10000000000000000000 10000000000000000000000000000000

输出

8
10000000000010000000000000000000

题目思路

这题就是道大整数计算,是到模板题,这道题只用到了加法,在这里有加、减、乘、除、取模、输入、输出等一系列的运算,但是仅限制正整数的运算。

代码如下

#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
using namespace std;
const int MAXN = 10000;
struct BigInteget
{
    int digit[MAXN];
    int length;
    BigInteget();
    BigInteget operator =(string str);
    BigInteget operator +(const BigInteget & b);
    friend istream& operator>>(istream& in, BigInteget& x);
    friend ostream& operator<<(ostream& out, const BigInteget& x);
};

istream& operator>>(istream& in, BigInteget& x)
{
    string str;
    in >> str;
    x = str;
    return in;
}

ostream& operator<<(ostream& out, const BigInteget& x)
{
    for(int i = x.length-1; i >= 0; i--)
        out << x.digit[i];
    return out;
}

BigInteget::BigInteget()
{
    memset(digit, 0, sizeof(digit));
    length = 0;
}
BigInteget BigInteget::operator=(string str)
{
    memset(digit, 0, sizeof(digit));
    length = str.size();
    for(int i = 0; i < length; i++)
        digit[i] = str[length-i-1] - '0';
    return *this;
}

BigInteget BigInteget::operator+(const BigInteget& b)
{
    BigInteget answer;
    int carry = 0;
    for(int i = 0; i < length || i < b.length; i++)
    {
        int current = carry + digit[i] + b.digit[i];
        carry = current /10;
        answer.digit[answer.length++] = current%10;
    }
    if(carry)
    {
        answer.digit[answer.length++] = carry;
    }
    return answer;
}

int main()
{
    BigInteget a, b;
    while(cin >> a >> b)
        cout << a + b << endl;
    return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bep_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值