OR operation in Java(BitSet.class)

2019-04-12 20:10发布

How to Write a program which will take 001010101110000100100...., 011100010001000011000...., 000000000010000000000100.... as input (bit) and the output will be OR of these 3.

OR = 0 0 = 0,
     0 1 = 1,
     1 0 = 1,
     1 1 = 1,

if sombody has a sample program that would be helpful too. Do we need to store the values in bit array from byte?

标签: java bitset
2条回答
Summer. ? 凉城
2楼-- · 2019-04-12 20:53

This should work (update: bug fixed):

public static BitSet or(final String... args){
    final BitSet temp = createBitset(args[0]);
    for(int i = 1; i < args.length; i++){
        temp.or(createBitset(args[i]));
    }
    return temp;
}

private static BitSet createBitset(final String input){
    int length = input.length();
    final BitSet bitSet = new BitSet(length);
    for(int i = 0; i < length; i++){
        // anything that's not a 1 is a zero, per convention
        bitSet.set(i, input.charAt(length - (i + 1)) == '1');
    }
    return bitSet;
}

Sample code:

public static void main(final String[] args){
    final BitSet bs =
        or("01010101", "10100000", "00001010", "1000000000000000");
    System.out.println(bs);
    System.out.println(toCharArray(bs));
}

private static char[] toCharArray(final BitSet bs){
    final int length = bs.length();
    final char[] arr = new char[length];
    for(int i = 0; i < length; i++){
        arr[i] = bs.get(i) ? '1' : '0';
    }
    return arr;
}

Output:

{0, 1, 2, 3, 4, 5, 6, 7, 15}
1111111100000001

查看更多
【Aperson】
3楼-- · 2019-04-12 21:04

Can't you just call the or method in the BitSet class?

[edit] Assuming you wanted an example, something like this should work:

BitSet doOr( List<BitSet> setsToOr ) {
  BitSet ret = null ;
  for( BitSet set : setsToOr ) {
    if( ret == null ) {
      // Set ret to a copy of the first set in the list
      ret = (BitSet)set.clone() ;
    }
    else {
      // Just or with the current set (changes the value of ret)
      ret.or( set ) ;
    }
  }
  // return the result
  return ret ;
}
查看更多
登录 后发表回答