创建一个数组,它包含从0到N的二进制元素
create an array such that it contains elements from 0 to N in binary
我需要一个快速的算法,它将生成所有可能的数字,直到一个给定的数字N在二进制数组。
e.g N=3
Then the array should be {0,0,0},{0,0,1}.....{1,1,1}
N<=17.
我已经试过了,这是一个递归的解决方案。
void print_digits(int n, std::string const& prefix = "") {
if (!n) {
printf("%s,",prefix.c_str());
return;
}
print_digits(n-1, prefix + '0');
print_digits(n-1, prefix + '1');
}
c++中的所有整数都以二进制形式直接存储在内存中。因此,如果您只想存储N个数字,您应该将它们直接写入数组"原样"
std::vector<unsigned> Numbers;
// if N is length of the number, calculate the maximum as 2^N - 1
long long Max = 1 << N - 1;
for (unsinged i = 0; i < Max; ++i)
Numbers.push_back(i);
如果你想用二进制表示它们,它也很简单,即使你想自己编码。(请原谅,因为这只是一个简单的示例实现)
void PrintAsBits(unsigned value) {
for (int i = sizeof(unsigned) * 8 - 1; i >= 0; --i)
cout << ((1 << i) & value) ? 1 : 0;
cout << 'n';
}
如果有人关心的话,下面的代码实现了原始规范,它调用了一种方法来填充一个二维数组,其中每个值都以数字数组表示,其元素对应于其值的二进制数字,以大端序。
#include <iostream>
static const int DIGIT_COUNT = 10;
static const int VALUE_COUNT = 1 << DIGIT_COUNT;
unsigned char g_binarray[VALUE_COUNT][DIGIT_COUNT];
void Populate() {
for(int i=0; i<VALUE_COUNT; ++i) {
unsigned char (&curr)[DIGIT_COUNT] = g_binarray[i];
for(int di=0; di<DIGIT_COUNT; ++di) {
curr[di] = unsigned char((i >> (DIGIT_COUNT - 1 - di)) & 1);
}
}
}
void DumpArray() {
static const char *digits = "01";
for(int i=1; i<VALUE_COUNT; ++i) {
for(int di=0; di<DIGIT_COUNT; ++di) {
std::cout << digits[!!g_binarray[i][di]];
}
std::cout << " " << i << std::endl;
}
}
int main(int argc, char* argv[]) {
Populate();
DumpArray();
return 0;
}
正如我在一篇文章中所写的:
示例:如果需要长度为4的数组,则必须有2^4 = 16个不同的数组。
您可以使用以下简单的Java代码生成所有数组:
for (int i=0; i < 16; i++) {
System.out.println(Integer.toBinaryString(i));
}
命令的输出:
0 110 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111
相关文章:
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 从二进制文件中读取元素时引发异常(引发异常:读取访问冲突. _Pnext 0xB414D4)
- 如何在向量上进行二进制搜索以找到具有特定id的元素
- 二进制搜索不变以查找元素的首次出现
- 在查找子集中元素和元素数量之间的二进制比较背后的逻辑是什么?
- 将二进制操作员应用于数组中的每个元素
- 对大于属性的元素的矢量对象进行二进制搜索
- 如何使用二进制搜索将元素插入分类的向量
- 将二进制文件读取到向量元素的地址中
- 如何使用二进制索引树来计算小于索引值的元素数量
- C++二进制搜索无法正常工作-查找不在数组中的元素
- 在二进制搜索树中查找第二个最大元素
- n个元素上的二进制搜索树的数目
- 访问OpenCV中的Mat二进制图像元素
- 将 3d 数组元素从十六进制转换为二进制以获得 bmp
- 更改 O(log(n)) 复杂度中二进制堆元素的优先级
- 正在从二进制索引树中删除元素
- 使用fread读取二进制文件时,无法获得正确的元素计数
- 二进制搜索,用于查找排序数组中比给定值最小和最大的元素
- 如何在两个容器的元素之间执行成对二进制操作?