w3resource

JavaScript: Return values that are powers of two

JavaScript Math: Exercise-36 with Solution

Check If Number Is Power of Two

Write a JavaScript function to return powers of two values.

Test Data :
console.log(isPower_of_two(64));
true
console.log(isPower_of_two(94));
false

Sample Solution:

JavaScript Code:

// Define a function named isPower_of_two that checks if a given number is a power of two.
function isPower_of_two(num)
{
    // Check if num is not zero and if num bitwise AND with (num - 1) equals zero.
    // This condition checks if num has only one bit set to 1, which indicates it is a power of two.
    return num && (num & (num - 1)) === 0;
}

// Output the result of checking if 64 is a power of two to the console.
console.log(isPower_of_two(64));  
// Output the result of checking if 94 is a power of two to the console.
console.log(isPower_of_two(94));

Output:

true
false

Visual Presentation:

JavaScript: Math - Return values that are powers of two.

Flowchart: Flowchart: JavaScript Math: Return values that are powers of two

Live Demo:

See the Pen javascript-math-exercise-36 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that determines if a number is a power of two using bitwise manipulation.
  • Write a JavaScript function that recursively divides a number by 2 to verify if it is a power of two.
  • Write a JavaScript function that converts a number to its binary representation and checks for exactly one '1' bit.
  • Write a JavaScript function that uses logarithms to test if the base-2 logarithm of a number is an integer.

Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function for the Pythagorean theorem.
Next: Write a JavaScript function to limit a value inside a certain range.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.