实施后会找到一组的子集,但是有人可以解释if((i&(1<<j)) > 0)
正在做什么以及出于什么原因?
评论似乎没有帮助并尝试控制台日志记录,但仍然很难看到它正在做什么。
//Print all subsets of given set[]
static void printSubsets(char set[]) {
int n = set.length;
//Run a loop for printing all 2^n subsets one by one
for(int i=0; i<(1<<n); i++) {
System.out.print("{ ");
//Print current subset
for(int j=0; j<n; j++) {
//(1<<j) is a number with jth bit 1
//so when we 'and' them with the
//subset number we get which numbers
//are present in the subset and which are not
if((i&(1<<j)) > 0) {
System.out.print(set[j] + " ");
}
}
System.out.println("}");
}
}
public static void main(String args[]) {
char set[] = {'a', 'b', 'c'};
printSubsets(set);
}
答案 0 :(得分:1)
在子集中,每个元素可以存在,也可以不存在。因此每个元素只有两种可能的状态:in或out。如果我们查看从0到ProducerThread
的数字的二进制表示,其中2^n -1
是元素的数量,例如当n
时,我们有:
n=3
有8个可能的子集,这些位表示元素是否在子集中。 这是该计划使用的想法:
cba
0 = 000
1 = 001
2 = 010
3 = 011
4 = 100
5 = 101
6 = 110
7 = 111
到0
。2^n-1
到0
。n-1
向左移动1<<j
次。例如,j
时,对应于位i=3
。
我们从011
循环到0
,将2
与i
,001
和010
进行比较。
对于这些值,表达式100
将被评估为
分别为i & (1 << j)
,011 & 001 = 001
和011 & 010 = 010
。
前两个大于0,最后一个不大于0。
因此011 & 100 = 000
将打印System.out.print(set[j] + " ")
和a
。