我刚遇到一个问题; 在伪代码中很容易解决,但是当我开始在java中编码时; 我开始意识到我不知道从哪里开始......
这是我需要做的:
pha*_*ers 25
Java中的"正确"方法是使用Hunter McMillen指出的已经存在的BitSet类.如果你正在想出如何纯粹为了思考一个有趣的问题而管理一个大的位数组,那么计算一个字节数组中位的位置就是基本的模运算.
public class BitArray {
private static final int ALL_ONES = 0xFFFFFFFF;
private static final int WORD_SIZE = 32;
private int bits[] = null;
public BitArray(int size) {
bits = new int[size / WORD_SIZE + (size % WORD_SIZE == 0 ? 0 : 1)];
}
public boolean getBit(int pos) {
return (bits[pos / WORD_SIZE] & (1 << (pos % WORD_SIZE))) != 0;
}
public void setBit(int pos, boolean b) {
int word = bits[pos / WORD_SIZE];
int posBit = 1 << (pos % WORD_SIZE);
if (b) {
word |= posBit;
} else {
word &= (ALL_ONES - posBit);
}
bits[pos / WORD_SIZE] = word;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27317 次 |
| 最近记录: |