大整数加法

以前看到别人的大数运算,一直都没有自己动手实践过,今天看到论坛上有人提出类似的简化了的问题,顺手写了一个,感觉还行,记录下来,以供日后参考。


类:

#pragma once

#include <string>

class CInteger
{
public:
	CInteger(void) { _number = "0"; _carry = '0'; }
	CInteger(std::string& integer) { _number = integer; _carry = '0'; }
	CInteger(const char * integer) { _number = integer; _carry = '0'; }
	virtual ~CInteger(void){}

private:
	std::string			_number;
	char				_carry;
	inline char			decimal_add(char _left, char _right)
	{
		char _result = _left + _right - '0';
		if(_result > '9')
		{
			_result -= 10;
			_carry += 1;
		}
		return _result;
	}

public:
	void				decimal_add()
	{
		std::string::reverse_iterator itr_number = _number.rbegin();
		*itr_number = decimal_add(*itr_number, '1');
		while(_carry != '0')
		{
			char tmp_carry = _carry;
			_carry = '0';
			itr_number++;
			if(_number.rend() == itr_number)
			{
				_number.insert(_number.begin(), '0');
				itr_number = _number.rend() - 1;
			}
			*itr_number = decimal_add(*itr_number, tmp_carry);
		}
	}
	inline unsigned int length(){ return _number.size(); }
	inline std::string	number(){ return _number; }
};

测试代码:

// Testor.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "Integer.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
	CInteger integer("1");
	unsigned int n = 0;
	std::cout << "n =";
	std::cin >> n ;
	for(int i = 0; integer.length() <= n; i++)
	{
		std::cout << integer.number() << std::endl;
		integer.decimal_add();
	}
	return 0;
}



你可能感兴趣的:(大整数加法)