-
-
Notifications
You must be signed in to change notification settings - Fork 101
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfest
Description
Approach
-
A number
nis 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
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfest