-
-
Notifications
You must be signed in to change notification settings - Fork 88
231. Power of Two #109
Copy link
Copy link
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfest
Metadata
Metadata
Assignees
Labels
hacktoberest-acceptedhacktoberfest-acceptedhacktoberfest-acceptedhacktoberfesthacktoberfesthacktoberfest
Approach
A number
nis a power of two if:n > 0Trick: For powers of two,
n & (n - 1) == 0.Example:
n & (n-1) = 0000✅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)) == 0efficiently verifies this.Solution in Code