Tutorialspoint
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)
NumberHCL TechnologiesTutorix
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

  • 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

Steps to solve by this approach:

 Step 1: Check if n is less than or equal to 0. If so, return false as power of two must be positive.
 Step 2: Understand that powers of two in binary representation have exactly one bit set to 1.
 Step 3: Use the bitwise trick: n & (n-1) removes the rightmost set bit in the binary representation.
 Step 4: For powers of two, there's only one bit set to 1, so removing it will result in 0.
 Step 5: Return true if n & (n-1) equals 0, false otherwise.

Submitted Code :