requirements

Every non-negative integer N has its binary representation. For example, 5 can be represented as binary “101”, 11 as binary “1011”, and so on. Note that there is no leading zero in any binary representation other than N = 0.

The binary inverse represents changing every 1 to 0 and every 0 to 1. For example, the binary inverse of the binary number “101” is “010”.

Given a decimal number N, return the decimal integer corresponding to the inverse of its binary representation.

Example 1:

Input: 5 Output: 2 Explanation: The binary representation of 5 is "101", and its binary inverse is "010", which is the decimal 2.Copy the code

Example 2:

Input: 7 Output: 0 Explanation: the binary representation of 7 is "111", and its binary inverse code is "000", which is 0 in decimal.Copy the code

Example 3:

Input: 10 Output: 5 Explanation: the binary representation of 10 is "1010" and its binary inverse is "0101", which is 5 in decimal.Copy the code

The core code

class Solution:
    def bitwiseComplement(self, n: int) - >int:
        m = 1
        while m < n:
            m = m << 1
            m += 1
        return m-n 
Copy the code

Another solution

class Solution:
    def bitwiseComplement(self, n: int) - >int:
        b = bin(n)[2:]
        res = ""
        for char in b:
            if char =="0":
                res += "1"
            else:
                res += "0"
        return int(res,2)

Copy the code

In the first solution, we want to calculate the inverse code, which can be achieved by making the difference between the current data and all 1 data of equal digit. For example, the inverse code of 5(101) is to use 111-101 = 010(2). We need to pay attention to the way we construct all 1 data — shift. The second solution: int(STR,2) and bin strings, easier to understand.