Understanding and Optimizing the Code: Checking if a Number is a Power of Two

Akhil Kumar
TheCodingWay
Published in
3 min readOct 15, 2023

LeetCode Power Of Two 231

In this article, we will discuss an approach to solve this problem using JavaScript. We’ll also explore potential optimizations for the provided code snippet.

The Easy Way

var isPowerOfTwo = function(n) {
if(n == 1)
return true;
if(n <= 0)
{
return false;
}
while(n >= 0)
{
if(n == 0 || n == 1)
{
return true;
}
if(n%2 != 0)
{
return false;
}
n = n/2;
}
return true;
};

Approach Explanation

The provided code attempts to determine if a given number n is a power of two. It employs a simple loop that divides n by 2 until n becomes less than or equal to zero. Along the way, it checks if n is 1 or 0, and returns true in those cases.

Let’s break down the code’s approach:

  1. If n is 1, the function immediately returns true since any number raised to the power of 0 is 1.
  2. If n is less than or equal to 0, the function returns false because negative numbers and zero cannot be powers of two.
  3. The while loop iterates as long as n is greater than or equal to zero.
  4. In each iteration, it checks if n is 0 or 1 and returns true in those cases.
  5. If n is not 0 or 1, it checks if n is divisible by 2 (n%2 != 0). If not, it means n is not a power of two, so it returns false.
  6. If n is divisible by 2, it divides n by 2 (n = n/2) and continues the loop.
  7. If the loop completes without finding any condition that triggers a return, it assumes n is a power of two and returns true.

Potential Optimizations

While the provided code works, it can be optimized for both readability and performance. Here is an improved version:

/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfTwo = function(n) {
if (n <= 0) {
return false;
}
return (n & (n - 1)) === 0;
};

Optimized Approach Explanation

The optimized code employs a bitwise operation to check if n is a power of two. Specifically, it uses the bitwise AND operation (&) between n and n - 1.

Here’s how it works:

  1. If n is less than or equal to 0, it immediately returns false, eliminating the need for a separate condition.
  2. The expression (n & (n - 1)) performs a bitwise AND operation between n and n - 1. This operation only results in 0 if n is a power of two.
  3. If the result of the bitwise AND operation is 0, the function returns true, indicating that n is a power of two.
  4. If the result is non-zero, it means n is not a power of two, and the function returns false.

Conclusion

The optimized approach provides a more concise and efficient solution to the problem. It leverages bitwise operations to determine if a given number is a power of two. This approach is not only more elegant but also performs better, especially for large inputs. Always remember to choose an approach that best suits the specific requirements and constraints of your application. Happy Coding!!

AI Generated “Happy Coding”

--

--