I am solving a ‘hackerRank’ coding challenge (basic) using JavaScript. the problem is,
You will be given a list of 32 bit unsigned integers. Flip all the bits (1->0 and 0->1) and return the result as an unsigned integer.
here is my code (I aware that i tried a cumbersome way and there is a very easy single line to code as well return (~n >>> 0)
function flippingBits(n) {
function dtb(num){
let rem = 0 ;
let i = 0;
let op = 0;
while(num !== 0){
rem = num % 2;
op = op + (rem*(Math.pow(10,i)));
i++;
num = Math.floor(num/2);
}
return String(op).padStart(32,'0');
}
function toggle(n){
let newOp = dtb(n);
let finalOp = '';
for(let i=0;i<newOp.length;i++){
if(newOp[i] === '1'){
finalOp += '0';
} else {
finalOp += '1';
}
}
return finalOp;
}
function btd(n){
let num = toggle(n);
let op = 0;
for(let i=0;i<num.length;i++){
op = op + (Math.pow(2,(num.length- 1)-i)*num[i]);
}
return op;
}
return btd(n);
}
the inputs that passed
enter image description here
the inputs that failed
Input (stdin)
3
0
802743475
35601423
my Output (stdout)
4294967295
4292350879
4293886735
Expected Output
4294967295
3492223820
4259365872