0

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

comatoad
  • 23
  • 4
  • 1
    Certainly *alternative* techniques are possible. But parsing the string would also take linear time, the loop is just shoved under the rug, in the form of calling a built-in function. Anything not string-based would have to do that as a first step, so (despite my bias towards bit-manipulation) it just seems pointless. – harold Aug 05 '22 at 00:51
  • I came to the same conclusion. I did some tests the other day (this question was driving me mad) and came to the conclusion that any alternate would be verbose, and ultimately moot in terms of performance increase - if any was to be found. It was a fun deep dive into more complicated bit-manipulation, but the readability of the traditional loop wins me over on this one. – comatoad Aug 06 '22 at 01:03
  • [This snippet](https://stackoverflow.com/a/10936810/1048572) uses `.replace(/[01]/g, d => +!+d)` for that purpose. Let me know how that fares in your speed tests! But no, you cannot improve complexity over a looping approach, any solution will be linear in the length of the input string. – Bergi Aug 06 '22 at 04:18
  • One critical question that needs to be asked is the maximum binary string value expected, as for reasonable limits, a Map object can then suffice leading to O(1) performance... – Trentium Sep 04 '22 at 13:26

1 Answers1

0

After ostensible testing, I have come to the conclusion that (for this particular instance) looping remains the most idiomatic, performant way to complete this binary operation. Any alternative solution was complex, and the tested op/s was negligible. Retaining a simple loop for string manipulation and memoizing remains the most performant option I tested.

comatoad
  • 23
  • 4