(一)大数据的应用
很多时候我们会面临计算机内置数据类型不够用的情况,比如说我们要统计全世界QQ用户的年访问量,这个数据将非常的庞大,VS开发平台最大的整型是long long 其范围是最大值9223372036854775807,最小值-9223372036854775808。16进制表示最大值0x7ffffffffffffff最小值为0x8000000000000000。
(二)自定义类型
BigData的实现思路,当处理的数据没有超过内置类型时,将数据保存到longlong类型中,超过范围时以字符串的形式保存到string类中,需要四则运算时,再将每一位转为数字进行运算。其实思路就是这么简单,难点在于实现的细节。
(四)初始化方式
定义两个构造函数,传参如果是范围内的数识别为BigData(INT64 data = UN_INIT),如果超出范围识别为BigData(const char *pData)
(三)加减法的实现
1.两个数都没有超(又分为计算结果有没有超):内置类型相加
2.两个数都超了(结果必然超了)
3.两个数有一个超了(结果必然超了)
以上三种情况下再考虑符号,减法考虑的情况与之类似
小技巧:运算传参时可以将位数长的数据固定传到左边的参数,方便逐位相加,还有更多的细节问题请看代码的注释
(四)乘法的实现
分情况的方式与加减法相似,乘法主要思路是逐位相乘,错位相加。
(五)除法的实现相对复杂些
如果被除数短,自然商为0,余数为该数。被除数长则计数除数的位数,再与被除数循环相减并补位(规则同除法运算一致)。
BigData.h
#ifndef BIG_DATA_H
#define BIG_DATA_H
#include <string>
#include <iostream>
#define UN_INIT 0xcccccccccccccccc//定义随机值
#define MAX_INT64 0x7fffffffffffffff//longlong类型的最大值
#define MIN_INT64 0x8000000000000000//longlong类型的最小值
typedef long long INT64;
class BigData
{
public:
BigData(INT64 data = UN_INIT);
BigData(const char *pData);
BigData operator+(BigData& bigData);
BigData operator-(const BigData& bigData);
BigData operator*(const BigData& bigData);
BigData operator/(const BigData& bigData);
BigData operator%(const BigData& bigData);
//=======================================
bool operator<(const BigData& bigData);
bool operator>(const BigData& bigData);
bool operator==(const BigData& bigData);
std::ostream& operator<<(std::ostream& _cout);
friend std::ostream& operator<<(std::ostream& _cout, const BigData& bigData);
friend std::istream& operator>>(std::istream& _cin, BigData bigData);
private:
std::string Add(std::string left, std::string right);
std::string Sub(std::string left, std::string right);
std::string Mul(std::string left, std::string right);
std::string Div(std::string left, std::string right);
void INT64ToString();
bool IsINT64Owerflow()const;
bool IsLeftStrBig(char *pLeft, size_t LSize, char *pRight, size_t RSize);
char SubLoop(char *pLeft, size_t LSize, char *pRight, size_t RSize);
private:
long long m_llValue;
std::string m_strData;
};
#endif
#include "BigData.h"
#include <cassert>
BigData::BigData(INT64 data)
: m_llValue(data)
, m_strData("")
{
INT64ToString();//作用是将内置类型数据转换成字符串存起来
}
BigData::BigData(const char *_pData)
{
// "-12345789" "1234567" "+" "12457aaa123" "000001234567"
// "a23456789"
// atoi
assert(NULL != _pData);
char cSybom = _pData[0];//保存这个数的符号
char* pData = (char*)_pData;//const char* 强转为char*
if ('+' == cSybom || '-' == cSybom)
{
pData++;
}
else if (*pData >= '0' && *pData <= '9')//根据输入将其转换成统一格式,将符号放在第0位
{
cSybom = '+';
}
else
{
m_llValue = 0;//输入是其他字符这个数字直接存成0
m_strData = "0";
return;
}
// 去掉前置0
while ('0' == *pData)
pData++;
// "12457aaa123"
m_strData.resize(strlen(pData) + 1);
m_llValue = 0;
m_strData[0] = cSybom;
int iCount = 1;
while (pData)//用于跳过输入中不合法的数字
&n