Contact: aviboots(AT)netvision.net.il
41,439 questions
53,986 answers
573 users
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 */
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 */