
Problem
Solution
Submissions
Power of Two
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 8
Write a JavaScript program to determine if a given positive integer is a power of two. A number is a power of two if it can be expressed as 2^n where n is a non-negative integer.
Example 1
- Input: n = 16
- Output: true
- Explanation:
- We need to check if 16 can be expressed as 2^n.
- 16 = 2^4, so it is a power of two.
- We can verify: 2 * 2 * 2 * 2 = 16.
- Therefore, 16 is a power of two.
- We need to check if 16 can be expressed as 2^n.
Example 2
- Input: n = 6
- Output: false
- Explanation:
- We need to check if 6 can be expressed as 2^n.
- The powers of 2 near 6 are: 2^2 = 4 and 2^3 = 8.
- Since 6 falls between 4 and 8, it cannot be expressed as 2^n.
- Therefore, 6 is not a power of two.
- We need to check if 6 can be expressed as 2^n.
Constraints
- -2^31 ≤ n ≤ 2^31 - 1
- Handle negative numbers and zero appropriately
- 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
- Use bit manipulation for an efficient solution
- A power of two has exactly one bit set in its binary representation
- Use the property: n & (n-1) == 0 for powers of two
- Handle edge cases like negative numbers and zero
- Ensure the number is positive before applying bit manipulation