Skip to content

231. Power of Two #109

@harshitap1305

Description

@harshitap1305

Approach

  • A number n is a power of two if:

    • n > 0
    • In binary, it has exactly one set bit.
  • Trick: For powers of two, n & (n - 1) == 0.

Example:

  • n = 8 (1000), n-1 = 7 (0111), n & (n-1) = 0000
  • n = 6 (0110), n-1 = 5 (0101), n & (n-1) = 0100

Intuition

Binary representation of powers of two looks like: 1 (0001), 2 (0010), 4 (0100), 8 (1000), 16 (10000) ...

Each has exactly one set bit.
Therefore, checking (n > 0) && (n & (n-1)) == 0 efficiently verifies this.


Solution in Code

class Solution {
public:
    bool isPowerOfTwo(int n) {
        if (n <= 0) return false;
        return (n & (n - 1)) == 0;
    }
};

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions