Java(BitSet.class)中的OR操作

如何编写一个程序,将001010101110000100100 ….,011100010001000011000 ….,000000000010000000000100 ….作为输入(位),输出将是这3个的OR.

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

如果某人有一个示例程序也将有所帮助.我们是否需要将值从字节存储到位数组中?

解决方法:

这应该可以工作(更新:已修复错误):

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;
}

样例代码:

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;
}

输出:

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

上一篇:STLのbitset


下一篇:Codeforces 1097F. Alex and a TV Show