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 −

 Live Demo

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

Updated on: 20-Apr-2021

51 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements