How to find the complement of a number in JavaScript

2 Answers

0 votes
function findComplement(num) {      
    let sum = 1, power = 1;
        
    while (sum < num) {
          power *= 2;
          sum += power;
    }
        
    return sum - num;
} 
    
  
const n = 12; // 1100 Complement = 0011 = 3

console.log(findComplement(n));
 
 
 
 
 
/*
run:
   
3
   
*/

 



answered Dec 5, 2021 by avibootz
edited Dec 5, 2021 by avibootz
0 votes
function findComplement(num) {      
    const number_of_bits = Math.floor(Math.log2(num)) + 1;
    
    return ((1 << number_of_bits) - 1) ^ num;
} 
     
   
const n = 12; // 1100 Complement = 0011 = 3
 
console.log(findComplement(n));
  
  
  
  
  
/*
run:
    
3
    
*/

 



answered Dec 5, 2021 by avibootz
edited Dec 5, 2021 by avibootz

Related questions

2 answers 193 views
2 answers 150 views
2 answers 131 views
2 answers 155 views
2 answers 135 views
2 answers 184 views
2 answers 130 views
...