Power of Two - Problem

Given an integer n, return true if it is a power of two. Otherwise, return false.

An integer n is a power of two if there exists an integer x such that n == 2^x.

Examples:

  • n = 1true (because 2^0 = 1)
  • n = 16true (because 2^4 = 16)
  • n = 3false (no integer x exists)

Input & Output

Example 1 — Power of Two
$ Input: n = 1
Output: true
💡 Note: 1 is 2⁰, so it's a power of two
Example 2 — Perfect Power
$ Input: n = 16
Output: true
💡 Note: 16 is 2⁴, so it's a power of two
Example 3 — Not a Power
$ Input: n = 3
Output: false
💡 Note: 3 cannot be expressed as 2^x for any integer x

Constraints

  • -2³¹ ≤ n ≤ 2³¹ - 1

Visualization

Tap to expand
Power of Two - Count Set Bits Approach INPUT Integer n = 1 1 Binary Representation: 0 0 0 1 2^3 2^2 2^1 2^0 Input Values: n = 1 binary: 0001 ALGORITHM STEPS 1 Check n greater than 0 n=1 is positive: OK 2 Count set bits (1s) Loop through all bits count = 0 bit 0: 1 --> count = 1 Only ONE bit is set! 3 Verify count equals 1 Power of 2 has 1 set bit 4 Return result count==1 ? true : false count(1) == 1 1 == 1 --> TRUE FINAL RESULT Is 1 a power of two? TRUE 1 = 2^0 Powers of Two: 2^0 = 1 --> 0001 2^1 = 2 --> 0010 2^2 = 4 --> 0100 2^3 = 8 --> 1000 Output: true Key Insight: A power of two in binary has exactly ONE bit set to 1. For example: 1=0001, 2=0010, 4=0100, 8=1000. Non-powers like 3=0011 have multiple bits set. Time Complexity: O(log n) | Space Complexity: O(1) TutorialsPoint - Power of Two | Count Set Bits Approach
Asked in
Google 25 Amazon 32 Microsoft 18 Apple 15
89.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen