简体   繁体   中英

Highest power of two but smaller than given BigInteger

I need to find highest power of two but smaller than given BigInteger. I have written following method for the same and it works, just wondering does better solution or even different solution exists?

 private static BigInteger getHighestPowerOf2(BigInteger bigInteger)
    {
    int bitLength = bigInteger.bitLength();
    for (int index = 0; index < (bitLength - 1); index++)
        bigInteger = bigInteger.clearBit(index);
    return bigInteger;
    }

As I am dealing which large number which exceeds limit of long and int so I cannot use & operator. I am using Java 7. Thanks in advance.

What about using setBit to set one bit instead of clearing a lot of bits?

private static BigInteger getHighestPowerOf2(BigInteger bigInteger)
{
   int bitLength = bigInteger.bitLength();
   return BigInteger.ZERO.setBit(bitLength-1);
}

您的方法在每次对clearBit调用中创建一个新的BigInteger ,因此效率不高。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM