印度阿三数据结构——链表——大整数算法


#pragma once
#include "stdafx.h"
class GREAT_INT_COMPUTE;
GREAT_INT_COMPUTE operator+(const GREAT_INT_COMPUTE&,const GREAT_INT_COMPUTE&);


class GREAT_INT_COMPUTE
{
public:
	friend GREAT_INT_COMPUTE operator+(const GREAT_INT_COMPUTE&, const GREAT_INT_COMPUTE&);
	//friend GREAT_INT_COMPUTE operator-(GREAT_INT_COMPUTE, GREAT_INT_COMPUTE);
	//friend GREAT_INT_COMPUTE operator*(GREAT_INT_COMPUTE, GREAT_INT_COMPUTE);
	GREAT_INT_COMPUTE(const GREAT_INT_COMPUTE&);
	GREAT_INT_COMPUTE(int *,int);
	~GREAT_INT_COMPUTE();
	void output();

//private:
	GREAT_INT_COMPUTE(const char*const(&), const int&);
	bool check(){}
	char* operand=nullptr ;
	int(*arr) = nullptr;
	int arrLen = 0;
};

#include "stdafx.h"
#include "GREAT_INT_COMPUTE.h"
using std::cin; using std::cout; using std::ends; using std::endl; using std::atoi;


GREAT_INT_COMPUTE::GREAT_INT_COMPUTE(const char*const(&c) ,const int& len)
{
	operand = new char[len];
	for (int i = 0; i != len; ++i){
		operand[i] = c[i];
	}
	arr = new int[len/3+1];
	for (int i = 0; i != len / 3 + 1; ++i)arr[i] = 0;
	int i = len - len % 3-1, j=len/3;
	for (; i >=0; --i){
		char* temp = new char[4];
		temp[2] = operand[i]; temp[1] = operand[--i]; temp[0] = operand[--i];
		temp[3] = '\0';
		arr[j--] = atoi(temp);
		delete[]temp;
	}
	if (j == 0){
	char *temp = new char[3]; j = 0;
	for (; j <= i; ++j){
		temp[j] = operand[j];
	}
	temp[j] = '\0';
	arr[0] = atoi(temp);
	}
	arrLen = len / 3 + 1;
}


GREAT_INT_COMPUTE::GREAT_INT_COMPUTE(int *a, int len){
	arr = new int[len];
	for (int i = 0; i != len; ++i){
		arr[i] = a[i];
	}
	arrLen = len;
	delete a;
}


GREAT_INT_COMPUTE::GREAT_INT_COMPUTE(const GREAT_INT_COMPUTE& g){
	arr = new int[g.arrLen];
	for (int i = 0; i != g.arrLen; ++i){
		arr[i] = g.arr[i];
	}
	arrLen = g.arrLen;
}


GREAT_INT_COMPUTE::~GREAT_INT_COMPUTE()
{
	delete operand;
	delete[]arr;
}


void GREAT_INT_COMPUTE::output(){
	for (int i = 0; i != arrLen ; ++i){
		cout << arr[i] << ends;
	}


}








//interface functions
GREAT_INT_COMPUTE operator+(const GREAT_INT_COMPUTE& g1,const GREAT_INT_COMPUTE& g2){
	int max = g1.arrLen > g2.arrLen ? g1.arrLen : g2.arrLen;
	int len = max;
	int*save = new int[max];
	int len1 = g1.arrLen-1, len2 = g2.arrLen-1;
	int value = 0;
	while (len1>=0&&len2>=0){
		if (g1.arr[len1] + g1.arr[len2]+value > 999){
			save[(max--)-1] = g1.arr[len1--] + g1.arr[len2--] +value- 1000;
			value = 1;
		}
		else {
			save[(max--)-1] = g1.arr[len1--] + g1.arr[len2--]+value;
			value = 0;
		}
	}
	if (len1 < 0){
		for (len2; len2 >= 0; --len2){
			save[max-- - 1] = g2.arr[len2]+value;
			value = 1;
		}
	}
	else if (len2 < 0){
		for (len1; len1 >= 0; --len1){
			save[max-- - 1] = g1.arr[len1]+value;
			value = 0;
		}
	}
	return GREAT_INT_COMPUTE(save, len);
}


匆忙一下午,大型修改了很多次,初期没有打草稿就是真么碍事,到现在只实现了加法;还是不带符号的;

 
 

你可能感兴趣的:(印度阿三数据结构——链表——大整数算法)