Use Bitwise Operation for Power of Two
In this step, we will explore a clever way to determine if a number is a power of two using bitwise operations in Java. This method is often more efficient than traditional loop-based approaches.
First, let's understand what a power of two is. A power of two is any number that can be expressed as 2 raised to an integer exponent (e.g., 2^0 = 1, 2^1 = 2, 2^2 = 4, 2^3 = 8, and so on). In binary representation, powers of two have a unique pattern: they are represented as a 1
followed by zero or more 0
s (e.g., 1 is 1
, 2 is 10
, 4 is 100
, 8 is 1000
).
Now, consider the binary representation of a power of two and the number immediately preceding it. For example:
- 8 in binary is
1000
- 7 in binary is
0111
If we perform a bitwise AND operation (&
) between a power of two and the number immediately preceding it, the result is always zero. This is because the power of two has a single 1
bit, and the number before it has 0
s in that position and 1
s in all the positions to the right.
For example, 8 (1000
) & 7 (0111
) = 0000
(which is 0).
This property holds true for all positive powers of two. Any positive number that is not a power of two will have at least two 1
bits in its binary representation. When you perform a bitwise AND with the number before it, at least one of those 1
bits will align with a 1
bit in the preceding number, resulting in a non-zero value.
So, the condition for a positive number n
to be a power of two is (n & (n - 1)) == 0
.
Let's create a Java program to implement this check.
-
Open the HelloJava.java
file in the WebIDE editor.
-
Replace the existing code with the following:
public class HelloJava {
// Function to check if a number is a power of two using bitwise AND
public static boolean isPowerOfTwo(int n) {
// A number is a power of two if it's positive and (n & (n - 1)) is 0
return (n > 0) && ((n & (n - 1)) == 0);
}
public static void main(String[] args) {
int number1 = 8;
int number2 = 12;
int number3 = 1;
System.out.println(number1 + " is a power of two: " + isPowerOfTwo(number1));
System.out.println(number2 + " is a power of two: " + isPowerOfTwo(number2));
System.out.println(number3 + " is a power of two: " + isPowerOfTwo(number3));
}
}
In this code:
- We define a static method
isPowerOfTwo
that takes an integer n
as input.
- Inside the method, we check if
n
is greater than 0 and if the bitwise AND of n
and n-1
is equal to 0.
- The
main
method demonstrates how to use the isPowerOfTwo
method with a few example numbers.
-
Save the file (Ctrl+S or Cmd+S).
-
Compile the Java program in the Terminal:
javac HelloJava.java
If there are no errors, the compilation is successful.
-
Run the compiled program:
java HelloJava
You should see output similar to this:
8 is a power of two: true
12 is a power of two: false
1 is a power of two: true
This output confirms that our bitwise check correctly identifies powers of two.