Easy Python Solution | O(1)T, O(1)S | Explanation
The idea is to XOR the number with a mask. The mask should contain all 1\'s in it\'s rightmost bits. Here, the number of 1\'s is important. For example: for the
The idea is to XOR the number with a mask. The mask should contain all 1\'s in it\'s rightmost bits. Here, the number of 1\'s is important. For example: for the number 5 (101), the mask should be 7 (111) which contains only 3 1\'s because the number 5 uses only 3 rightmost bits. Now when we XOR 5 and 7, we get 2:\n101 -> 5\n111 -> 7\n---- (XOR)\n010 -> 2\n\nIn positive integers, the rightmost bit is always set to 1. The idea is to use this bit to set all the other bits to 1. For example, if we take an 8-bit number 10000000, we can perform the following operations to generate the mask:\n\nStep 1 : mask |= mask >> 1\n10000000\n&nbsp;&nbsp;1000000 (OR)\n\\------------\n11000000\n\nStep 2 : mask |= mask >> 2\n11000000\n&nbsp;&nbsp;&nbsp;&nbsp;110000(OR)\n\\------------\n11110000\n\nStep 3 : mask |= mask >> 4\n11110000\n&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1111(OR)\n\\------------\n11111111\n\nThe number (11111111) generated above is the mask. Now all we have to do is XOR this mask with the original number. This operation will invert all the bits in the original number.\n\nThe above number was 8 bit integer, therefore we got the mask in 3 steps. If the number was 32 bit, we would get the mask in the 5th step where we right-shift the number by 16.\n\n```\ndef bitwiseComplement(self, N: int) -> int:\n    if N == 0:\n        return 1\n        \n    mask = N\n    mask |= mask >> 1\n    mask |= mask >> 2\n    mask |= mask >> 4\n    mask |= mask >> 8\n    mask |= mask >> 16\n        \n    return N ^ mask\n```
['Bitmask']