【发布时间】:2016-11-20 10:24:09
【问题描述】:
以下实现会找到集合的子集,但谁能解释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);
}
【问题讨论】:
-
“子集的子集”是什么意思?这会打印给定集合的所有子集(至少对于小型集合,有一次您会用完
int中的位)。 -
@Thilo 抱歉打错了,意思是集合的子集。