[英]OR operation in Java(BitSet.class)
如何編寫一個程序,它將取001010101110000100100
...., 011100010001000011000
...., 000000000010000000000100
....作為輸入(位),輸出將是這些3的OR
。
OR = 0 0 = 0,
0 1 = 1,
1 0 = 1,
1 1 = 1,
如果sombody有一個樣本程序也會有幫助。 我們需要將值存儲在字節中的位數組中嗎?
[編輯]假設你想要一個例子,這樣的事情應該有效:
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 ;
}
這應該工作( 更新:錯誤修復):
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.