Check Power of 2 in Java
What you’ll learn
- How powers of two look in binary (single set bit).
- How the trick
n & (n - 1)works. - How to validate input and test range values quickly.
What is power of 2?
A number is a power of 2 if it can be written as 2^k for a whole number k.
Examples: 1, 2, 4, 8, 16, 32. Non-examples: 3, 6, 10, 12.
Prerequisites
Binary intuition, bitwise operators, and integer boundaries.
- Binary representation basics and set bits.
- Java bitwise operators
&and subtraction. - Difference between positive, zero, and negative values.
Intuition and examples
A positive power of two has exactly one 1 bit in binary. So n & (n - 1) becomes 0 only for powers of two.
Algorithm
- If
n <= 0, return false. - Compute
n & (n - 1). - If the result is
0, thennis a power of 2; otherwise not.
📜 Pseudocode
Pseudocode
function isPowerOfTwo(n):
if n <= 0:
return false
return (n & (n - 1)) == 01
Check one number
This checks whether 16 is a power of 2.
java
public class Main {
static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
public static void main(String[] args) {
int number = 16;
if (isPowerOfTwo(number)) {
System.out.println(number + " is a power of 2.");
} else {
System.out.println(number + " is not a power of 2.");
}
}
}2
Power of 2 in range 1 to 20
This prints all powers of 2 from 1 to 20.
java
public class Main {
static boolean isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}
public static void main(String[] args) {
System.out.println("Power of 2 in the range 1 to 20:");
for (int i = 1; i <= 20; i++) {
if (isPowerOfTwo(i)) {
System.out.print(i + " ");
}
}
}
}Live preview
Enter any integer and test if it is a power of 2.
Optimization tips
Prefer the bit trick for single checks: n > 0 && (n & (n - 1)) == 0.
Use divide-by-2 loop only when bitwise operators are restricted.
❓ FAQ
A number is a power of 2 if it can be written as 2^k for some whole number k (for example 1, 2, 4, 8, 16).
Yes. 1 = 2^0.
A positive power of two has exactly one set bit in binary. n & (n - 1) clears the lowest set bit; for powers of two the result becomes 0.
Because 0 and negative numbers are not treated as powers of two in this interview definition.
Yes. Repeatedly divide by 2 while number is even, and check whether you end at 1.
Bitwise method is O(1). Divide-by-2 loop is O(log n).
Input/output examples
| Input n | Output |
|---|---|
16 | Power of 2 |
18 | Not a power of 2 |
1 | Power of 2 |
Edge cases
One
1 is valid
1 = 2^0, so result is true.
Zero/Negative
Not powers of two
Return false when n <= 0.
⏱️ Time and space complexity
| Method | Time | Extra space |
|---|---|---|
Bitwise n & (n - 1) | O(1) | O(1) |
| Repeated divide-by-2 loop | O(log n) | O(1) |
Summary
- Use
n > 0 && (n & (n - 1)) == 0for the cleanest solution. - This check is constant time and interview-friendly.
Did you know?
Many computer concepts naturally use powers of two, like memory sizes and bit masks.
8 people found this page helpful
