algorithm - finding the common parent of multiple BitSets java -
i couldn't find proper solution simple question in bitset methods. question find common parent of bitsets, starting left bit. here examples:
011 010 001 common parent: 0 00 010 common parent: 0 00 11 10 common parent: none 1101 111 1100 common parent: 11
my solution , bitsets, , find correct length looking first set bit on xor of these bitsets. worked cases failed others. have idea involves looping on bitsets happy avoid if have solution.
[i know can presented binary tree, involves memory overhead avoid operating on bitsets , boolean operations (and, or, nor, nand, xor)]
you example this:
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 min length of inputs n=math.min(n,in.length()); // if start counting indices left, need reverse inputs string reverse = new stringbuilder(in).reverse().tostring(); // create 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"); // can print indices if needed. }
i wrote few comments in code. hope helps!
Comments
Post a Comment