## 1. Introduction

A power of 2 is a number that can be expressed as 2 raised to some integer power, such as 2, 4, 8, 16, and so on. In Java, there are several ways to determine if a given number is a power of 2, including using logarithms, bitwise operations, loop division, and built-in methods. In this tutorial, we’ll explore these different methods and provide examples of how to implement them in Java.

## 2. Loop Division

One way to check if a number is a power of 2 is to iteratively divide the number by 2 until it reaches 1. If the number is a power of 2, it’ll result in 1 after a finite number of divisions. Let’s see how this technique is implemented:

``````boolean isPowerOfTwoUsingLoopDivision(int n) {
while (n != 1 && n % 2 == 0) {
n /= 2;
}
return n == 1;
}``````

In this method, we use a while loop to divide the number by 2 until it becomes 1. If the number is a power of 2, then it’ll be divided only a few times before it becomes 1. However, for the number that is not a power of 2, the loop will keep dividing until it encounters an odd number:

``````assertTrue(isPowerOfTwoUsingLoopDivision(256));
assertFalse(isPowerOfTwoUsingLoopDivision(100));``````
By repeatedly halving the number until it reaches 1, we determine if it is a power of 2. This approach is straightforward, but it may introduce complexity and inefficiency, particularly for larger numbers, due to repeated divisions.

## 3. Using Bitwise & Operations

A more efficient method involves leveraging bitwise operations. In binary representation, a power of 2 has only one set bit (1) and all other bits set to 0. This characteristic allows us to exploit bitwise operators for a faster solution. Let’s implement this technique:

``````boolean isPowerOfTwoUsingBitwiseOperation(int n) {
return (n != 0) && ((n & (n - 1)) == 0);
}``````

This method first checks if n is not zero (since zero isn’t a power of 2). Then, it uses the bitwise AND operator (&) to perform a clever trick. The expression n & (n – 1) essentially turns off the least significant set bit in n. If n was a power of 2 with only one set bit, this operation would result in zero. This is because both numbers will have their single set bits at different positions, leading to a 0 after the AND operation:

``````assertTrue(isPowerOfTwoUsingBitwiseOperation(256));
assertFalse(isPowerOfTwoUsingBitwiseOperation(100));``````

This approach is fast and efficient due to its simplicity and by leveraging a bitwise operation. However, it might be less intuitive for beginners and require a basic understanding of bitwise operations.

## 4. Counting Set Bits

This method involves counting the number of set bits (1s) in the binary representation of the number. Since a power of 2 has only one set bit, counting the set bits can reveal if the number is a power of 2. Here’s an example implementation:

``````boolean isPowerOfTwoUsingSetBitCount(int n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count == 1;
}
``````

This approach iterates through each bit of n to check if it’s set (1) using the bitwise AND with 1 (n & 1). It then accumulates the count of set bits. Next, we shift the bits of n to the right by one position using the right shift operator (>>). This operation effectively moves to the next bit in the binary representation of n.

After processing all bits, it checks if the count is equal to 1, indicating a power of 2:

``````assertTrue(isPowerOfTwoUsingSetBitCount(256));
assertFalse(isPowerOfTwoUsingSetBitCount(100));``````

This method might be useful in scenarios where counting set bits is required for other purposes.

## 5. Using Integer.highestOneBit()

Java provides a built-in method Integer.highestOneBit(int) that returns the integer with the highest bit set (leftmost 1) to 1 and all lower bits set to 0. Let’s see how we can leverage this method:

``````boolean isPowerOfTwoUsingHighestOneBit(int n) {
return n > 0 && (n == Integer.highestOneBit(n));
}``````

This method ensures n is positive and compares n with the result of Integer.highestOneBit(). If n is a power of 2, it’ll have only one set bit, and both values will be equal:

``````assertTrue(isPowerOfTwoUsingHighestOneBit(256));
assertFalse(isPowerOfTwoUsingHighestOneBit(100));``````

By ensuring the number is positive and comparing it with its highest set bit, this approach offers a concise solution. However, it might entail slightly more overhead compared to bitwise operations.

## 6. Using Logarithm

Lastly, we can use the logarithm base 2 to check the power of 2. The base-2 logarithm of a number is the exponent to which 2 must be raised to get that number. If the logarithm (base 2) of a number is a whole number, then the number is a power of 2. Here’s the Java code demonstrating this method:

``````boolean isPowerOfTwoUsingLogarithm(int n) {
return (Math.log(n) / Math.log(2)) % 1 == 0;
}``````

In this method, we divide the natural logarithm of n by the natural logarithm of 2 Math.log(2). If the result is a whole number, then the number is a power of 2. We use the modulo operator % to check if the result is a whole number. If the result is 0, then the number is a power of 2:

``````assertTrue(isPowerOfTwoUsingLogarithm(256));
assertFalse(isPowerOfTwoUsingLogarithm(100));``````

The advantage of this method is that it is easy to understand and implement. However, it can be slower for large numbers.

## 7. Summary

Each approach has its advantages and considerations. Here’s a summary.

Loop Division Straightforward concept. Inefficient for larger numbers due to repeated divisions.
Bitwise AND Efficient and fast due to bitwise operations. Can be less intuitive for beginners.
Counting Set Bits Useful when counting set bits is required for other purposes. More complex than bitwise AND.
highestOneBit() Concise and readable code. Might have slightly more overhead.
Logarithm Easy to understand and implement. Slower for large numbers.

## 8. Conclusion

In this article, we’ve explored a few ways to determine if a number is a power of 2 in Java. For most applications, bitwise operations are the most efficient and effective method.

As always, the source code for the examples is available over on GitHub.

### Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
Subscribe
Notify of
1 Comment
Inline Feedbacks