Member-only story

Coding Interview Prep: HackerRank’s Flipping Bits Solution in JavaScript

Marika Lam
Jun 25, 2024

--

Prompt

Solution

  1. Convert the string to bits using toString(2)
  2. Create the string of 0s to create a 32 bit length string
  3. Concatenate the string of 0s with the converted bits
  4. Go through the 32 bit string number by number using charAt() and flip 0s to 1s and 1s to 0s.
  5. Convert the 32 bit string back to an integer using parseInt(number, 2).
function flippingBits(n) {
const createZeros = (num) => {
let res = "";

for (let i=num; i<32; i++){
res = res+"0";
}
return res;
}
// Write your code here
const toBits = Number(n).toString(2);
console.log(toBits.length);

const zeros = createZeros(toBits.length);
const toBitsWithZeros = zeros+toBits;
console.log(toBitsWithZeros);

let resNum = "";
for (let j=0; j<32; j++){
if (toBitsWithZeros.charAt(j) == "0"){
resNum += "1";
} else {
resNum += "0";
}
}
console.log(resNum);
const flip = parseInt(resNum, 2);
console.log(flip);
return flip;
}

--

--

No responses yet