Java finds all subsets of a set through bit operation

Java does not have its own method to find all subsets of a set. We can find them through the subset law of the set.

All subsets of a set are equal to 2 ^ the length of the set. For example, if the length of {C, B, a} is 3, there are 8 subsets of this set.

This sentence looks very simple, but it also implies profound philosophy. In fact, all sets of a set are related to the number 2 ^ the length of the set. For example, in the above example, if the length of {C, a} is 3, all its subsets can be represented by 0-7. As shown below, changing the position corresponding to the number to 1 indicates that I need this number to form a subset. The binary representation from 0 to 7 just represents all subsets with a length of 3 and a subset number of 8.

0(000):{}

1(001):{a}

2(010):{b}

3(011):{ab}

4(100):{c}

5(101):{a,c}

6(110):{b,c}

7(111):{a,c}

Therefore, according to the above rules, the code can be written as follows: first take the length of the set, find 2 ^ the length of the set, such as 8 above, and then traverse from 0 to 8-1. During traversal, perform bit operation on 0, 1, 2... Each data, and judge its corresponding bit one by one, that is, the binary representation. That bit is 1. Use the assembly method to shift each bit to the end, and implement the bit sum of 1. The specific code is as follows:

The operation results are as follows:

The above method of finding all subsets of a set through bit operation in Java is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>