
Problem
Solution
Submissions
Power of Two
Certification: Basic Level
Accuracy: 14.29%
Submissions: 7
Points: 5
Write a Java program to determine whether an integer is a power of two. An integer is a power of two if there exists an integer x such that n = 2^x.
Example 1
- Input: n = 16
- Output: true
- Explanation:
- Step 1: 16 can be expressed as 2^4.
- Step 2: 2^4 = 2 * 2 * 2 * 2 = 16
- Step 3: Therefore, 16 is a power of two.
Example 2
- Input: n = 218
- Output: false
- Explanation:
- Step 1: 218 cannot be expressed as 2^x for any integer x.
- Step 2: The closest powers of two are 2^7 = 128 and 2^8 = 256.
- Step 3: Since 218 falls between these two powers, it is not a power of two.
Constraints
- -2^31 ≤ n ≤ 2^31 - 1
- Time Complexity: O(1)
- Space Complexity: O(1)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- If n is a power of two, it has exactly one bit set to 1 in its binary representation
- Use bitwise operations to check this property
- Handle edge cases like n = 0 separately
- Use the property that n & (n-1) for powers of two equals zero