Solution Review: Power of 2

Let's see how we make use of Brain Kernighan's algorithm to achieve this.

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:

202^{0}, 212^{1}, 222^{2}, 232^{3}, 242^{4} 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), return True
  • 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.