结构体实现大整数运算

大整数(高精度整数)

<一>

1.以结构体

// 1. 结构体存储 struct


const int maxn=1000+10;
struct BigInteger{
	int bign[maxn];
	int length;
	BigInteger(){
		memset(bign,0,sizeof(bign));  //构造函数 
		length=0;
	}
}; 

结构体初始化方法:

  1. 构造函数
  2. 初始化列表

1.先字符串输入

声明string 读入大整数

(字符数组)

string str; cin>>str;

2.然后转化至BigInteger

<二>

定义;

输入流(运算符重载)


istream& operator >> (istream &in, BigInteger& x) {
  string s;
  if(!(in >> s)) return in;
  x = s;
  return in;
}
//        输入流 (运算符重载)

输出流重载

ostream& operator << (ostream &out, const BigInteger& x) {
  out << x.s.back();
  for(int i = x.s.size()-2; i >= 0; i--) {
    char buf[20];
    sprintf(buf, "%08d", x.s[i]);
    for(int j = 0; j < strlen(buf); j++) out << buf[j];
  }
  return out;
}

附加:
大整数–结构体完整实现

#include<iostream>
#include<string>
#include<cstring>

using namespace std;

const int maxn = 1000 + 10;
char ch[maxn];

struct big_number{
	int nub[maxn];
	int length;
	big_number(){
		memset(nub, 0, sizeof(nub));
		length = 0;
	}
};


big_number change(char a[]){
	big_number b;
	b.length = sizeof(a);
	for (size_t i = 0; i < sizeof(a); i++)
	{
		b.nub[i] = a[b.length-i-1] - '0';
	}
	return b;
}

big_number add(big_number a, big_number b){
	big_number c;
	int carry=0;
	for (int i = 0; i < a.length || b.length; ++i){
		int temp = a.nub[i] + b.nub[i]+carry;
		c.nub[c.length++] = temp % 10;   // big_number Length默认为0
		carry = temp / 10;  // carry新的进位
	}
	if (carry!=0){
		c.nub[c.length++] = carry;
	}
	return c;
}

big_number sub(big_number a, big_number b){  //a-b
	big_number c;
	for (int i = 0; i < a.length || b.length; ++i){
		if (a.nub[i] < b.nub[i]){
			a.nub[++i]--;
			a.nub[i] += 10;
		}
		c.nub[c.length++] = a.nub[i]-b.nub[i];   // big_number Length默认为0	
	}
	//去高位0
	while (c.length>1&&c.nub[c.length-1]==0){
		c.length--;
	}
	return c;
}

big_number multi(big_number a, int b){
	big_number c;
	int carry=0;
	for (size_t i = 0; i < a.length; i++)
	{
		int temp = a.nub[i] * b + carry;
		c.nub[c.length++]=temp%10;
		carry = temp / 10;
	}
	while (carry != 0){
		c.nub[c.length++] = carry % 10;
		carry /= 10;
	}
	return c;
}


//输出函数
void print(big_number x){
	for (size_t i = 0; i < x.length; i++)
	{
		cout << x.nub[x.length-1-i] - '0';
	}
}

int main(){
	char str1[maxn], str2[maxn];
	cin >> str1 >> str2;
	big_number a = change(str1);
	big_number b = change(str2);

	print(add(a, b));
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值