Member-only story
Solution to Leetcode problem 1012: Complement of Base 10 Integer
In this Leetcode problem, we are given an integer N
and we should return the integer representing the complement of its base 2 representation. For instance, with the input 5
, the binary representation of 5 is 101
, the complement of 101
is 010
, which represents the integer 2
. Therefore for input 5
the output should be 2
.
One idea would be to take N
, find its binary representation bin_str
, then change all the ‘0’s in ‘1’s and the ‘1’s in ‘0’s. Then find the int_val
of the binary string obtained, and return it. That would be the most natural solution and I encourage you to try it out.
Another way, that is commonly applied for solution where we use binary representation of integers, is to find a ‘clever’ mask and apply it for a bitwise operation. Here, we will find out that once we analyze the problem correctly the mask isn’t that clever.
As mentioned before, we want to turn each 1
in the binary string representation into 0
and vice versa. In other words we want an operation corresponding to the truth table:
input | output
-----------------
0 | 1
1 | 0
To do this we are given this set of bitwise operations in Go:
& bitwise AND
| bitwise OR
^ bitwise XOR
&^ AND NOT
<< left shift
>>…