我有一个 for
循环生成整数。
例如:
for (int i=300; i>200; i--)
{(somefunction)*i=n;
cout<<n;
}
这会在屏幕上产生这样的输出:
f=00000000000100023;
我想将这个数字的 100023 部分存储为一个数组(即忽略非零数字开始之前的所有零,然后保留后面的零)。
像这样:
array[0]=1;
array[1]=0;
array[2]=0;
array[3]=0;
array[4]=2;
array[5]=3;
我将如何实现这一目标?
最佳答案
这是一大堆答案,因为它们都在那里,我只是认为您没有看到解决方案。
首先,如果它们是整数 Bill's answer连同其他答案都很棒,请将其中一些答案跳过“存储在数组中”部分。另外,正如在对您的问题的评论中指出的,这部分是 a duplicate .
但是对于您的新代码,我想到的解决方案是 John's solution .您只需要弄清楚如何忽略前导零,这很简单:
std::vector<int> digits;
bool inNumber = false;
for (int i=300; i>200; i--)
{
int value = (somefunction) * i;
if (value != 0)
{
inNumber = true; // its not zero, so we have entered the number
}
if (inNumber)
{
// this code cannot execute until we hit the first non-zero number
digits.push_back(value);
}
}
基本上,在达到实际数字之前不要开始插入。
关于c++ - 如何从循环生成的整数中删除前导零并将其存储为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/879375/