[Python] XOR masking explained
For easy writing num is written as n\n\nSo the agenda of the question is to flip all the bits of given number. i.e., \nn = 4 (100) => 3 (011)\n\nOne way of ache
*For easy writing num is written as n*\n\nSo the agenda of the question is to flip all the bits of given number. i.e., \n` n = 4 (100) => 3 (011)`\n\nOne way of acheving it is **xor between the number and its mask**, i.e.,  `100 ^ 111 == 011`\n\n* **So now how to get its mask ?**\n\t* A simple way would be to initialize mask = 0 and keep flipping bits of it to 1 starting from the rightmost bit (LSB) till we reach the leftmost set bit of num.\n\n* **Now, how do we know that we reached the leftmost set bit in num?**\n\t* We use another variable temp = n. Each time, we will rightshift temp essentially removing the rightmost bit. When we remove the leftmost set bit from it, it will become 0. Thus, we loop till temp is not 0.\n\n* **What if initially n = 0?**\n\t* We handle that case in the start itself, so that there wont be any uncertainity.\n\n```\nclass Solution:\n    def bitwiseComplement(self, n: int) -> int:\n        if not n: return 1\n        mask = 0\n        temp = n\n        while temp:\n            mask = (mask << 1) | 1\n            temp >>= 1\n        return n ^ mask\n```\n*Time complexity : O(N) where N = length of bits\nSpace complexity: O(1)*\n\n ***Upvote, if this helped.***\n\n\n\n
['Bit Manipulation', 'Python']