Suppose we have a number in decimal number system. We have to get the complement of the number in binary form, then again change it to decimal and return the result. So if the number is 20, then the binary form will be 10100, the complement will be 01011, this is 11 in decimal
To solve this, we will follow these steps −
- s := binary string of the number n
- sum := 0 and num := 1
- for each element i in s in reverse direction
- if i = ‘b’, then return sum
- otherwise when i = ‘0’, then sum := sum + num
- num := num * 2
Example
Let us see the following implementation to get better understanding −
class Solution(object): def bitwiseComplement(self, N): s = str(bin(N)) sum = 0 num = 1 for i in s[::-1]: if i == "b": return sum elif i =="0": sum+=num num*=2 ob1 = Solution() print(ob1.bitwiseComplement(20))
Input
20
Output
11