
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check 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