用C ++强大的功能 [英] Power very large number in C++
本文介绍了用C ++强大的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一点时间的人可以向我解释一下如何增加非常大的数字吗?我在这里不是在谈论一个现成的解决方案,而是关于如何实现该算法的唯一解释.理想情况下,它基于类std :: string.
Can someone with a bit of time, he could explain to me how intensify very large numbers? I'm not talking here about a ready solution, and the only explanation of how to implement the arithmetic. Ideally, it was based on the class std::string.
@edit
我阅读了一些有关移位位的信息,但示例仅以清单的形式出现,我想解释它的工作原理.
I read something about shifts bit, but examples were only in the form of a listing, and I want an explanation of how it works.
推荐答案
以下是我在需要时快速写的内容(不记得何时).它是:
Here is something I quickly wrote when I needed (do not remember when). It is:
- 越野车;
- 不完整;
- 每个数组元素任意使用3位数字,但可以使用更多位;
- 可以明显改善(欢迎任何形式的评论^^).
但是,我希望这会有所帮助.
However, I hope this will be somehow useful.
typedef long long int lli;
class BigInt
{
public: // Methods
BigInt(lli s) : m_nbElements(100)
{
m_number.resize(m_nbElements);
for (lli i=0; i < m_nbElements; ++i)
{
m_number[i] = s%1000;
s /= 1000;
}
}
BigInt(const std::string &str) : m_nbElements(100)
{
m_number.resize(m_nbElements);
size_t sizeStr = str.size();
int i = str.size() - 1;
int thousands = 0;
for (; i >= 2; i -= 3, ++thousands)
{
std::string subStr = str.substr(i-2, 3);
unsigned int value;
std::istringstream(subStr) >> value;
m_number[thousands] = value;
}
// Handle the "first" 1 or 2 digits
if (i >= 0)
{
std::string subStr = str.substr(0, i+1);
unsigned int value;
std::istringstream(subStr) >> value;
m_number[thousands] = value;
}
}
BigInt operator*(lli s)
{
lli temp, remainder = 0;
for (lli i=0; i < m_nbElements; ++i)
{
temp = m_number[i] * s + remainder;
m_number[i] = temp % 1000;
remainder = temp / 1000;
}
return (*this);
}
BigInt operator/(lli s)
{
lli temp, remainder = 0;
for (int i=m_nbElements-1; i >= 0; --i)
{
temp = (m_number[i] + remainder) / s;
remainder = (m_number[i] % s)*1000;
m_number[i] = temp;
}
return (*this);
}
BigInt operator-(BigInt s)
{
lli temp;
for (unsigned int i=0; i < m_nbElements; ++i)
{
temp = m_number[i] - s.m_number[i];
if (temp < 0)
{
--m_number[i+1];
temp += 1000;
}
m_number[i] = temp;
}
return (*this);
}
BigInt operator+(BigInt s)
{
lli temp, remainder = 0;
for (lli i=0; i < m_nbElements; ++i)
{
temp = m_number[i] + s.m_number[i] + remainder;
m_number[i] = temp % 1000;
remainder = temp / 1000;
}
return (*this);
}
std::string ToString()
{
std::string result = "";
bool significantDigitsFound = false;
for (int i=m_nbElements-1; i >= 0 ; --i)
{
if (!significantDigitsFound)
{
if (m_number[i] > 0)
{
std::ostringstream ss;
ss << m_number[i];
result = ss.str();
significantDigitsFound = true;
}
}
else
{
std::ostringstream ss;
ss << std::setw(3) << std::setfill( '0' ) << m_number[i];
result += ss.str();
}
}
if (result == "")
{
result = "0";
}
return result;
}
private: // Attributes
int m_nbElements;
std::vector<lli> m_number;
};
这篇关于用C ++强大的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文