- Related Questions & Answers
- C program for Addition and Multiplication by 2 using Bitwise Operations.
- Nearest power 2 of a number - JavaScript
- Performing power operations on an array of numbers in JavaScript
- Reordered Power of 2 in C++
- Checking if a number is some power of the other JavaScript
- Checking if a number is a valid power of 4 in JavaScript
- Checking for the similarity of two 2-D arrays in JavaScript
- Performing Bitwise Operations with BigInteger in Java
- Check if bitwise AND of any subset is power of two in Python
- C/C++ Program to Find sum of Series with n-th term as n power of 2 - (n-1) power of 2
- Checking for vowels in array of numbers using JavaScript
- Check if n is divisible by power of 2 without using arithmetic operators in Python
- Check if given number is a power of d where d is a power of 2 in Python
- Compute modulus division by a power-of-2-number in C#
- How to multiply a given number by 2 using Bitwise Operators in C#?

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

We are required to write a JavaScript function that takes in a number and determines whether or not it is a power of two.

**For example −**

f(23) = false f(16) = true f(1) = true f(1024) = true

**Approach −**

Powers of two in binary form always have just one bit. Like this −

1: 0001 2: 0010 4: 0100 8: 1000

Therefore, after checking that the number is greater than zero, we can use a bitwise hack to test that one and only one bit is set. The same is shown below −

num & (num - 1)

Following is the code −

const num1 = 256; const num2 = 1024; const isPowerOfTwo = (num = 1) => { if (num < 1) { return false; }; return (num & (num - 1)) === 0; }; console.log(isPowerOfTwo(num1)); console.log(isPowerOfTwo(num2)); console.log(isPowerOfTwo(1)); console.log(isPowerOfTwo(23));

Following is the output on console −

true true true false

Advertisements