Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Checking power of 2 using bitwise operations in JavaScript
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)
Example
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));
Output
Following is the output on console −
true true true false
Advertisements
