The Power of two algorithm is a very interesting question that you may have heard in your school or college asked in many interviews including FAANG companies.


The question for an algorithm is,


Given a positive integer, write a function to find if it is a power of two or not.


Example 1:

Input: n = 64

Output: true


Example 2:

Input: n = 94

Output: false


Let's start with the algorithm,


var  isPowerTwo = function(n) {

  // 1 (2^0) is the smallest power of two.

  if (n < 1) {

    return false;

  }

  // Let's find out if we can divide the number by two

  // many times without remainder.

  while (n !== 1) {

    if (n % 2 !== 0) {

      // For every case when remainder isn't zero we can say that this number

      // couldn't be a result of power of two.

      return false;

    }

    n /= 2;

  }

  return true;

}; 


Here, we just keep dividing the number by two unless the number becomes 1 and every time we do so, we check that remainder after division is always 0. Otherwise, the number can't be a power of two.


I hope you understood the algorithm. If you have any doubts, please let us know in the comments.