JavaScript - Check a number is a power of 4 or not

JavaScript Bit Manipulation: Exercise-6 with Solution

Write a JavaScript program to check a given positive number is a power of four or not using bit manipulation.

The expression n & (n-1) will unset the rightmost set bit of a number. If the number is a power of 2, it has only a 1-bit set, and n & (n-1) will unset the only set bit. So, we can say that n & (n-1) returns 0 if n is a power of 2; otherwise, it's not a power of 2.
The mask 0xAAAAAAAA will allow us to determine where the set bit is located. In all of its odd positions, the mask 0xAAAAAAAA has a value of 1. The set bit in n will be even if the expression (n & 0xAAAAAAAA) is true.
(0xAAAAAAAA)16 = (10101010101010101010101010101010)2.

Test Data:
(256) -> true
(4) -> true
(2) -> false
("16") -> "It must be number!"

Sample Solution:

JavaScript Code:

const Power_of_four = (n) => {
      if (typeof n!= "number") {
          return 'It must be number!'
 return n != 0 && (n & (n - 1)) == 0 && (n & 0xAAAAAAAA) == 0;

Sample Output:

It must be number!


Flowchart: JavaScript - Check a number is a power of 4 or not.

Live Demo:

See the Pen javascript-bit-manipulation-exercise-6 by w3resource (@w3resource) on CodePen.

* To run the code mouse over on Result panel and click on 'RERUN' button.*

Improve this sample solution and post your code through Disqus

Previous: Odd or even number using bit manipulation.
Next: Swap two bits at given position in an integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

function and arguments

const person = {
  name: 'Lydia Hallie',
  hobbies: ['coding'],

function addHobby(hobby, hobbies = person.hobbies) {
  return hobbies;

addHobby('running', []);
addHobby('baking', person.hobbies);


The addHobby function receives two arguments, hobby and hobbies with the default value of the hobbies array on the person object.
First, we invoke the addHobby function, and pass "running" as the value for hobby and an empty array as the value for hobbies. Since we pass an empty array as the value for y, "running" gets added to this empty array.
Then, we invoke the addHobby function, and pass "dancing" as the value for hobby. We didn't pass a value for hobbies, so it gets the default value, the hobbies property on the person object. We push the hobby dancing to the person.hobbies array.
Last, we invoke the addHobby function, and pass "bdaking" as the value for hobby, and the person.hobbies array as the value for hobbies. We push the hobby baking to the person.hobbies array.
After pushing dancing and baking, the value of person.hobbies is ["coding", "dancing", "baking"]

Ref: https://bit.ly/2Hcpkm6