Solution Review: Power of 2
Let's see how we make use of Brain Kernighan's algorithm to achieve this.
We'll cover the following
Solution review: Brian Kernighan’s algorithm
This is considered faster than the previous naive approach.
In this approach, we count the set bits. If a number is the power of 2, we know that only one set bit is present in its Binary representation.
In binary, we go from right to left with powers of 2.
For example:
, , , , and so on…
Algorithm
Before we talk about algorithmic steps, you should review the table data and slider shown below the table.
- if
(n & (n - 1) == 0)
, returnTrue
- else,
False
Let’s visualize the values in the table below:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.