数字的加减乘除是在程序设计中必不可少的一部分,但是整数的加法存在一定的缺陷,一般情况下整数的加法完全可以满足日常的使用,但是一旦超过一定的数值之后,就会出现数值的溢出,就不能完成得到正确的数值,所以大数的加法就具有一定的意义。
大数的加法首先要考虑数位和数据溢出的问题,当两个整数的加法的和超出当前整数所表达的最大的值时,就需要向前进一位,现在采用每个整数来表示十进制中的数字位,进制也是2的32次方.
#pragma once
//大数管理类
#define MAX_INT_COUNT 1000
class BigInt {
public:
BigInt();
~BigInt();
BigInt operator+(const BigInt&value);
private:
unsigned int _length = 0;//整数位数
unsigned int _value[MAX_INT_COUNT];//数位
};
#include "BigInt.h"
#include <string.h>
BigInt::BigInt() {
memset(_value, 0, MAX_INT_COUNT * sizeof(unsigned int));
}
BigInt::~BigInt() {
}
BigInt BigInt::operator+(const BigInt&value) {
BigInt result;
result._length = this->_length > value._length ? this->_length : value._length;
unsigned int carry = 0;//保存进位
for (int i = 0; i < result._length;i++) {
unsigned __int64 sum = value._value[i] + this->_value[i];
sum += carry;
result._value[i] = (unsigned int)sum;
carry = (unsigned int)(sum >> 32);//取得最高值
}
result._value[result._length] = carry;
result._length += carry;
return result;
}
aaa