Skip to content

Conversation

@harshitap1305
Copy link
Contributor

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;
    }
};

@harshitap1305
Copy link
Contributor Author

This closes issue: #110

@SjxSubham
Copy link
Owner

SjxSubham commented Oct 4, 2025

Hi @harshitap1305 thanks for the PR... each contributor are allowed to raise and solve upto 2 issues Only...
Give chance other participants too..

I hope You understand
and ### Star the repo as well ⭐

Happy HAcktober...

Thanks for the PRs #111 #76

@SjxSubham SjxSubham added the hacktoberest-accepted hacktoberfest-accepted label Oct 4, 2025
@SjxSubham SjxSubham linked an issue Oct 8, 2025 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

hacktoberest-accepted hacktoberfest-accepted

Projects

None yet

Development

Successfully merging this pull request may close these issues.

231. Power of Two

2 participants