Which number has more trailing zeros in binary representation

Viewed 64

Given two numbers, A and B, I am wondering what the most efficient way to determine which of them has more trailing zeros (in binary representation) using Java would be.

I could determine the number of trailing zeros for both of them individually, but I don't know if this is the best approach or if there is some binary magic that could do it better.

Note: the numbers can be very large, I need to use BigInteger.

1 Answers

Because you're using BigInteger, you can use BigInteger#getLowestSetBit to determine the number of zero bits to the right of the rightmost one bit.

System.out.println(BigInteger.valueOf(32).getLowestSetBit());

Output:

5

Note: this method returns -1 if the number contains no one bits (i.e. 0).

Related