w3resource

JavaScript: Test if a number is a power of 2

JavaScript Math: Exercise-13 with Solution

Write a JavaScript function to test if a number is a power of 2.

Test Data:
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256));
Output:
true
false
true

Visual Presentation:

JavaScript: Math - Test if a number is a power of 2.

Sample Solution-1:

JavaScript Code:

// Define a constant named power_of_2 using arrow function syntax that checks if a number is a power of 2.
const power_of_2 = n => !!n && (n & (n - 1)) == 0;

// Output the result of checking if 16 is a power of 2 to the console.
console.log(power_of_2(16));
// Output the result of checking if 18 is a power of 2 to the console.
console.log(power_of_2(18));
// Output the result of checking if 256 is a power of 2 to the console.
console.log(power_of_2(256));

Output:

true
false
true

Flowchart:

Flowchart: JavaScript Math-  Test if a number is a power of 2

Sample Solution-2:

JavaScript Code:

const power_of_2 = n => !!n && (n & (n - 1)) == 0;
console.log(power_of_2(16));
console.log(power_of_2(18));
console.log(power_of_2(256)); 

Sample Output:

true
false
true

Live Demo:

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


Improve this sample solution and post your code through Disqus.

Previous: Write a JavaScript function to find out if a number is a natural number or not.
Next: Write a JavaScript function to round a number to a given decimal places.

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://w3resource.com/javascript-exercises/javascript-math-exercise-13.php