Tutorialspoint
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.
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.
Constraints
  • -2^31 ≤ n ≤ 2^31 - 1
  • Handle negative numbers and zero appropriately
  • Time Complexity: O(1)
  • Space Complexity: O(1)
NumberIBMShopify
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Check if the number is positive (powers of two are always positive).

 Step 2: Use bit manipulation property: n & (n-1) should equal 0 for powers of two.
 Step 3: This works because powers of two have exactly one bit set in binary.
 Step 4: When we subtract 1 from a power of two, all bits after the set bit become 1.
 Step 5: The bitwise AND of n and (n-1) results in 0 for powers of two.
 Step 6: Return the result of the logical AND of both conditions.
 Step 7: Handle edge cases like 0 and negative numbers appropriately.

Submitted Code :