本文介绍了Java中的OR操作(BitSet.class)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写程序 001010101110000100100 ...., 011100010001000011000 ...., 000000000010000000000100 ....作为输入(位),输出将是这三个。

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,

如果sombody有一个有用的示例程序。我们是否需要将值存储在位数组中?

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

推荐答案

这应该有效(更新:错误修复):

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

示例代码:

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

输出:

这篇关于Java中的OR操作(BitSet.class)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:48