网易笔试题 | C++实现大数的加减法(代码详解)

这篇博客主要介绍了如何使用C++实现大数的加法和减法操作,包括大整数类的构造、输出运算符<<的重载、加号+和减号-运算符的重载函数的解题思路,以及测试主函数的代码和运行结果展示。
摘要由CSDN通过智能技术生成

大数运算-------加法/减法

题目描述

编程(网易笔试题): 请实现以下类的方法,完成大数的加减法(可以使用STL容器)
// 大整数类型
class BigInt
{
   
public:
	BigInt(string str) :strDigit(str){
   }
private:
	string strDigit; //使用字符串存储大整数
};
	// 打印函数
	ostream& operator<<(ostream &out, const BigInt &src);
	// 大数加法
	BigInt operator+(const BigInt &lhs, const BigInt &rhs);
	// 大数减法
	BigInt operator-(const BigInt &lhs, const BigInt &rhs);
int main()
{
   
	BigInt int1("28937697857832167849697653231243");
	BigInt int2("9785645649886874535428765");
	cout << int1 + int2 << endl;
	cout << int1 - int2 << endl;
	return 0;
}

通过代码我们来详细理解解题的整个思路

构造大整数类

#include "stdafx.h"
#include <iostream>
#include <algorithm> // 泛型算法的头文件
#include <string>
#include <vector>
// 定义了一个大整数类
class BigInt
{
   
public:
	BigInt(string str) :strDigit(str) {
   }
private:
	string strDigit;   // 使用字符串存储大整数
	//三个运算符重载函数要定义为友元函数
	friend ostream& operator<<(ostream &out, const BigInt &src);
	friend BigInt operator+(const BigInt &lhs, const BigInt &rhs);
	friend BigInt operator-(const BigInt &lhs, const BigInt &rhs);
};
输出运算符<<的重载函数
// 打印函数
ostream
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值