Java 支持较大数据类型的位旋转操作
我发现了一个很好的位旋转技术的Java实现,我想很多都是基于它的。特别是对于Java 支持较大数据类型的位旋转操作,java,bit-manipulation,bitwise-operators,long-integer,biginteger,Java,Bit Manipulation,Bitwise Operators,Long Integer,Biginteger,我发现了一个很好的位旋转技术的Java实现,我想很多都是基于它的。特别是对于toBitSet和nextpermutat,我想知道:有没有可能让它们支持超过64位(long)的数据类型?怎么做? 例如,可以为Java的BigInt定义这样的方法吗 或者,当nextPermutation正在执行时,对k位二进制字符串(长度为n)(其中k=#位设置为1,总共n=#位)进行迭代是否需要(较慢的)String实现(即,将二进制数表示为n个字符串) 下面是上述操作的来源。很抱歉,我不能添加更多信息,我很遗憾
toBitSet
和nextpermutat
,我想知道:有没有可能让它们支持超过64位(long
)的数据类型?怎么做?例如,可以为Java的
BigInt
定义这样的方法吗
或者,当nextPermutation
正在执行时,对k位二进制字符串(长度为n)(其中k=#位设置为1,总共n=#位)进行迭代是否需要(较慢的)String
实现(即,将二进制数表示为n个字符串)
下面是上述操作的来源。很抱歉,我不能添加更多信息,我很遗憾地承认,我对一般的位运算知之甚少。
如有任何建议,将不胜感激
托比特集:
nextPermutation:
你应该自己努力做到这一点。请检查文档中的
biginger
和BitSet
?课堂上,你自己努力做这件事,如果你被某个特定的问题困住了,那么问你的问题。你应该自己努力做这件事。请检查文档中的biginger
和BitSet
?同学们,你们自己努力吧,如果你们在某个特定的问题上陷入了困境,那个就去问你们的问题。
/**
* Converts {@code value} into a {@link BitSet} of size {@code size}.
*/
public static final BitSet toBitSet(final int size, final long value) {
BitSet bits = new BitSet(size);
int idx = 0;
long tmp = value;
while (tmp != 0L) {
if (tmp % 2L != 0L) {
bits.set(idx);
}
++idx;
tmp = tmp >>> 1;
}
return bits;
}
/**
* Compute the lexicographically next bit permutation.
*
* Suppose we have a pattern of N bits set to 1 in an integer and we want the next permutation of
* N 1 bits in a lexicographical sense. For example, if N is 3 and the bit pattern is 00010011,
* the next patterns would be 00010101, 00010110, 00011001,00011010, 00011100, 00100011, and so
* forth.
*/
public static final long nextPermutation(long val) {
long tmp = val | (val - 1);
return (tmp + 1) | (((-tmp & -~tmp) - 1) >> (Long.numberOfTrailingZeros(val) + 1));
}