Reputation: 3089
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.
Upvotes: 2
Views: 117
Reputation: 1180
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);
}
Upvotes: 3