是否 LargeInteger
相当于 BigInteger
's testBit
?
如果不是,怎么可能testBit
在 LargeInteger
上执行?
我还没有必要的技能来复制((this & (1<<n)) != 0)
.
我尝试通过复制和粘贴从文档中引用的上述代码来创建一个方法:
static boolean testBit(int n){
return ((this & (1<<n)) != 0);
}
但是,编译器报告:
error: non-static variable this cannot be referenced from a static context
return ((this & (1<<n)) != 0);
^
error: bad operand types for binary operator '&'
return ((this & (1<<n)) != 0);
^
最佳答案
这是我能想到的最好的 API:
static boolean testBit(LargeInteger i, int n) {
return i.shiftRight(n).isOdd();
}
n
是待测位的位置。
我假设您将此方法放在某个实用程序类中。
解释
通常,你会做 num & (1 << pos)
在 pos
处提取位当前位置:
???????x?????
0000000100000
-------------
0000000x00000
如果整个事情是 0 那么 x
为 0;否则,x
为 1。
在上面的方法中,我做 num >> pos
:
???????x?????
-------------
????????????x
我们知道二进制数的最低位为1时为奇数,最低位为0时为偶数。
所以如果右移后的数是奇数,我们就知道该位是1;如果偶数,我们知道该位为 0。
关于java - LargeInteger 相当于 BigInteger 的 testBit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21286794/