[英]finding the common parent of multiple BitSets java
我在Bitset方法中找不到這個簡單問題的正確解決方案。 問題是從最左邊的位開始找到位集的公共父節點。 這里有些例子:
011
010
001
Common Parent: 0
00
010
Common Parent: 0
00
11
10
Common Parent: None
1101
111
1100
Common Parent: 11
我的解決方案是AND位組,然后通過查找這些位組的XOR上的第一個設置位找到正確的長度。 它適用於某些情況,但其他情況則失敗。 我有另一個想法,涉及循環比特集,如果你有一個解決方案我會很樂意避免。
[我知道它們可以表示為二叉樹,但這涉及一個內存開銷,我希望通過僅操作位集和一些布爾操作(AND,OR,NOR,NAND,XOR)來避免這種情況。
你可以做一些像這樣的事情:
String[] input = {"011","010","001"};
if(input.length==0) return ;
int n=input[0].length();
List<BitSet> bitsets = new ArrayList<>();
for(String in:input){
// n is the min length of the inputs
n=Math.min(n,in.length());
// If you start counting the indices from the left, you need to reverse the inputs
String reverse = new StringBuilder(in).reverse().toString();
// Create the actual bitsets
BitSet b = BitSet.valueOf(new long[] { Long.parseLong(reverse, 2) });
bitsets.add(b);
}
for(int i=0;i<n;i++){
boolean equals=true;
for(int j=1;j<bitsets.size();j++)
equals &= bitsets.get(j-1).get(i)==bitsets.get(j).get(i);
if(equals)
System.out.print(bitsets.get(0).get(i)?"1":"0");
// You can also print the indices if needed.
}
我在代碼中寫了幾條評論。 我希望它有所幫助!
您可以AND
和OR
所有位集並存儲在兩個變量中。 從MSB
到LSB
同時迭代這兩個變量。 如果OR[i]
為0
,則所有位集在第 i 個位置都為0
。 如果AND[i]
為1
,則所有位集在該位置都有1
,否則它們是混合的。
我建議反轉數字並從右邊找到父母,然后將父母翻轉它以找到真實的東西。
我認為你遇到的最棘手的情況是
1101
111
1100
Common Parent: 11
和逆轉讓你擺脫它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.