- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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 if decimals share at least two common 1 bits in JavaScript
Problem
We are required to write a JavaScript function that takes in two numbers. Our function should return true if the numbers have 1 in the binary representation at the same index twice, false otherwise.
Example
Following is the code −
const num1 = 10; const num2 = 15; const checkBits = (num1 = 1, num2 = 1) => { let c = num1.toString(2).split(''); let d = num2.toString(2).split(''); if(c.length > d.length){ c = c.slice(c.length - d.length); }else{ d = d.slice(d.length - c.length); }; let count = 0; for(let i = 0; i < d.length; i++){ if(c[i] === "1" && d[i] === "1"){ count++; }; }; return count > 1; }; console.log(checkBits(num1, num2));
Output
Following is the console output −
true
Advertisements