- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- C program for Addition and Multiplication by 2 using Bitwise Operations.
- Performing power operations on an array of numbers in JavaScript
- Checking if a number is a valid power of 4 in JavaScript
- Checking if a number is some power of the other JavaScript
- Performing Bitwise Operations with BigInteger in Java
- Checking for vowels in array of numbers using JavaScript
- Nearest power 2 of a number - JavaScript
- Checking for the similarity of two 2-D arrays in JavaScript
- Using operations to produce desired results in JavaScript
- Check if bitwise AND of any subset is power of two in Python
- Checking validity of equations in JavaScript
- Checking the validity of parentheses in JavaScript
- Numbers obtained during checking divisibility by 7 using JavaScript
- Checking smooth sentences in JavaScript
- Explain about bitwise operators in JavaScript?

Advertisements