Given a integer number, n. What is the fastest way to inverse bits of that number? For example, if n = 5 (101) then output should be 2(010). Prefix 0
aren't considered for inverse. The unique part of this question is that here, we don't consider prefix 0
.
My approach:
Convert n to binary as a string. For example, if n = 5 then I'll have string, say str, as `101`.
Convert 1 to 0 and 0 to 1 in the string. (output: 010)
Convert resultant binary string to number. (output: 2)
More input/output examples:
Input: 7, Output: 0
Input: 8, Output: 7
Input: 10, Output: 5
Input: 98, Output: 29
As you can see, my approach looks naive or very inefficient. Is there a better way, by using some bit manipulation operation or any other way get desired output faster?
Note: n
can be negative as well! For negative number, 2's compliment has to be taken in to account for inverting the bits.
I'm not asking for exact code. Pseudo code or approach will be helpful.