为什么 C++ 中的矢量不会自动调整大小
Why vector in C++ doesn't resize automatically
我有一个很长的阶乘程序,需要查找最高100的阶乘。它可以很好地工作33个阶乘,但从34中却不能。有人可以帮助识别问题。
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void bigFactorials(int n)
{
vector<int> v;//If I specify the size as v(1000) it works fine but I don't
//want to specify the size beforehand.
v.push_back(1);
// Complete this function
for(int i=2;i<=n;i++) {
int carry = 0, mul=0;
for(auto j=v.rbegin();j!=v.rend();j++) {
mul=i**j + carry;
carry=mul/10;
*j=mul%10;
}
if(carry)
v.insert(v.begin(),carry);
}
for(int i:v)
cout<<i;
}
int main()
{
int n;
cin >> n;
if( n>0 && n<101 )
bigFactorials(n);
return 0;
}
问题是crand> 10时,然后插入一个整数值而不将其分成字符,应如下实现
if(carry)
{
if (carry >= 10)
{
while (carry > 0)
{
v.insert(v.begin(),carry % 10); // put each char from carry into v
carry = carry / 10;
}
}
else
v.insert (v.begin(),carry);
}
这样,您甚至可以将v
作为vector<char>
和50!我们有3041409320171337804361260816660647684444443776415689605120000000000000000000000000000000000000000000000000000000000来源。
当我打印出添加到向量的carry
值时,您肯定会溢出:
1
5
4
3
3
3
4
6
8
13
20
35
64
121
243
510
1124
2585
6204
15511
40329
108888
304888
884176
2652528
8222838
26313083
86833176
-134263930
-134263930-639604140847618609643520000000
我切换到vector和 carry
和 mul
的 long long
,并且能够获得34!的正确答案,但是99!仍然溢出。似乎您需要进一步减少要添加到向量的数字。
您需要以十进制数字分配carry
,然后在您的 bigint 中插入。。
while (carry)
{
v.insert(v.begin(), carry % 10);
carry /= 10;
}
在这里整个功能:
void bigFactorials(int n) {
vector<int> v;//If I specify the size as v(1000) it works fine but I don't
//want to specify the size beforehand.
v.push_back(1);
// Complete this function
for (int i = 2; i <= n; i++)
{
int carry = 0, mul = 0;
for (auto j = v.rbegin(); j != v.rend(); j++)
{
mul = i * *j + carry;
carry = mul / 10;
*j = mul % 10;
}
while (carry)
{
v.insert(v.begin(), carry % 10);
carry /= 10;
}
}
for (int i : v)
cout << i;
}
live demo
相关文章:
- 为char数组调整zlib-zpipe
- 调整大小后指向元素值的指针unordered_map有效?
- 在C++中调整向量中的索引
- 哪些库可以通过Opencv调整曝光率
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- Alt+Enter 在 Win32 应用中,管理大小调整和分辨率
- 在容量内调整矢量大小时的性能影响
- 将 boost::odeint 与向量类一起使用,而无需调整向量的大小
- 将摄像机调整到俯视图
- Qt 图表条形图调整大小崩溃
- 除非重新绘制大小,否则SDL_Texture在调整大小后呈现黑色
- 调整布局上的 QGraphicsView 小部件的大小
- 如何在构建链接列表时调整头、尾指针
- 如何将旧的 C 样式 #define 映射与现代C++进行调整?
- 当您在此单词中搜索单词时调整字符数组的大小?
- SDL2 调整窗口大小后如何缩放鼠标坐标?
- 如何按另一个向量的方向调整一个向量?
- 使用大小调整大小调整 wxListView 的大小
- 调整大小和复制哈希表数组中的元素
- 具有调整对齐方式的类型定义