DEV Community

Vibhor Singh
Vibhor Singh

Posted on

Flipping Bits Problem

This problem asks the solver to print the flipped bits of 32bit unsigned integer.

In detail, you would be provided an integer -

9 (base 10)

You have to write a function such that it returns the 32 bit unsigned decimal integer result -

4294967286 (base 10)

All code would be in Javascript but you can use any language to solve this problem.

How one goes from 9 to 4294967286?

  • first take the input and convert it a string using toString() function
 let s=n.toString(2);
Enter fullscreen mode Exit fullscreen mode
  • initialize a new variable and assign it to 32-(length of string)
 let temp=32-s.length;
Enter fullscreen mode Exit fullscreen mode

Why temp is equal to 32-s.length - variable s stores the number in binary format i.e. n=9 in decimal and s would store "1001" in binary {datatype of s is string here}, you are asked in this case to generate a 32 bit integer so to add the remaining bits in s, we assign temp to the given formula.

  • initialize a new variable and assign it to an empty string
let temp_s="";
for(let i=0;i<temp;i++)
    temp_s+="0";
Enter fullscreen mode Exit fullscreen mode

temp_s appends 0 to an empty string of length temp.

  • res_s would hold the string full of 0 and the converted string of the number in binary format
let res_s=temp_s+s; 
Enter fullscreen mode Exit fullscreen mode

res_s=00000000000000000000000000001001

  • flip_s would store the flipped string as 1 would convert to 0 and 0 to 1
let flip_s="";
Enter fullscreen mode Exit fullscreen mode
  • we use for of loop to traverse through string res_s
for(let i of res_s) {
        if(i==="0")
            flip_s+="1";
        else if(i==="1")
            flip_s+="0";
    }
Enter fullscreen mode Exit fullscreen mode

Here every element in the string is checked for 0 and 1 and assigned to 1 and 0 respectively.

flip_s=11111111111111111111111111110110

  • print the value of given expression on console/prompt screen
console.log( parseInt(flip_s, 2));
Enter fullscreen mode Exit fullscreen mode

Here, parseInt() method converts the flip_s variable to decimal form and output results in

4294967286

This problem is the part of HackerRank's 1 Month Interview Prep Kit.

Top comments (1)

Collapse
 
danyglez94 profile image
Daniel Gonzalez

Thank you! You gave me the main idea, and I ended up coding this, I think is easier to understand it like this.

function flippingBits(n) {
  const binaryString = n.toString(2).padStart(32, "0");
  const flippedString = binaryString
    .split("")
    .map((bit) => (bit === "0" ? "1" : "0"))
    .join("");
  const flippedNumber = parseInt(flippedString, 2);
  return flippedNumber;
}
Enter fullscreen mode Exit fullscreen mode