生成所有可能的0和& amp;组合的算法1s,对于任何长度的数字 [英] Algorithm to generate all possible combinations of 0s & 1s, for any length of digits
问题描述
我想知道如何打印n个1和0的组合.组合数n
是用户定义的.预期的输出是;
I would like to know how can I print n number of combinations of 1s and 0s. The number of combinations, n
is user defined. The expected outputs are;
n = 1;
0,1
n = 2;
00,01,10,11
n = 3;
000,001,010,011,100,101,110,111
等.等等.
输出将具有2^n
个组合数(其中n是单个组合中的预期位数).
The outputs will have 2^n
number of combinations (where n is the number of expected digits in a single combination).
如何在不使用任何内置函数的情况下执行此操作?这个问题与语言无关,是针对算法的.
How can I do this without using any built in function? The question is language independent and is for algorithm.
推荐答案
您可以枚举直到2^n - 1
的所有数字.这将使您拥有相同的组合.
You could just enumerate all numbers till 2^n - 1
in binary. That will leave you with the same combination.
n = 2
枚举直到2^3 - 1
= 7
转换为二进制:
n = 2
enumerate till 2^3 - 1
= 7
Convert to binary:
000 --> 0
001 --> 1
010 --> 2
011 --> 3
100 --> 4
101 --> 5
110 --> 6
111 --> 7
编辑:也修复了数字位数.可行
EDIT: Fixed the number of digits as well. This works
#include <stdio.h>
#define LENGTH 3
void print_binary(int n)
{
int bit = 1<<LENGTH - 1;
while ( bit ) {
printf("%d", n & bit ? 1 : 0);
bit >>= 1;
}
printf("\n");
}
int main(){
int n = 1<<LENGTH, i;
for(i=0;i<n;i++)
print_binary(i);
}
这篇关于生成所有可能的0和& amp;组合的算法1s,对于任何长度的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!