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.


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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-36.php