Flipping Bits Problem
Vibhor Singh
Posted on September 5, 2022
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);
- initialize a new variable and assign it to 32-(length of string)
let temp=32-s.length;
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";
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;
res_s=00000000000000000000000000001001
- flip_s would store the flipped string as 1 would convert to 0 and 0 to 1
let flip_s="";
- 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";
}
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));
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.
Posted on September 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.