1

LargeInteger有等价于BigInteger'stestBit吗?

如果没有,如何testBit在 a 上执行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);
                  ^
4

1 回答 1

3

给定 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。

于 2014-01-22T16:03:09.697 回答