Recently I was asked to take a binary string input 10
and NOT it so the output is 01
in Javascript. My initial thought - loop over the variables and manually flip the bits - cannot be the best solution to this problem.
I am fairly sure you can use the tilde (bitwise NOT) operator to some degree, but I am awful with bit manipulation and have struggled to do this operation properly in Javascript. How could I use tilde in this instance to invert the binary? I assume I would first convert the binary to a base ten number, invert it, and convert it back -- but is there an easy way to get it out of two's complement so my final result is still 01
?
Also, this was from an interview-style question, so I'm really looking to beat out the time complexity of looping through the array - any alternative methods would also be appreciated