✅100.0%🔥Easy Solution🔥With Explanation🔥
Intuition\n#### When asked to find the complement of an integer, the idea is to flip every bit in its binary representation\u2014changing 0s to 1s and 1s to 0s.
# Intuition\n#### When asked to find the complement of an integer, the idea is to flip every bit in its binary representation\u2014changing `0`s to `1`s and `1`s to `0`s. For example, the complement of 5 (which is `101` in binary) is `010`, which is `2` in decimal.\n---\n\n# Approach\n#### `Determine the Binary Length`: First, calculate the bit length of the integer. This is the number of bits required to represent the number in binary.\n#### `Create a Mask`: Generate a binary number (mask) that has all bits set to 1 for the same length as the number\'s binary representation. This mask helps in flipping all bits when XORed with the original number.\n#### `Flip the Bits`: Perform the XOR operation between the number and the mask. XORing with 1 flips the bit (0 becomes 1 and 1 becomes 0).\n#### `Return the Result`: The result of the XOR operation is the complement of the original number.\n---\n\n\n\n\n- # Time complexity:\n##### The time complexity is $$O(1)$$. The operations (finding bit length, shifting bits, XOR operation) are all constant time operations regardless of the size of the integer.\n- # Space complexity:\n##### The space complexity is $$O(1)$$. We are using a constant amount of extra space (only a few variables) that does not scale with the input size.\n---\n# Code\n```python []\nclass Solution:\n    def findComplement(self, num: int) -> int:\n        bit_length = num.bit_length()\n        \n        mask = (1 << bit_length) - 1\n        \n        return num ^ mask\n```\n```C++ []\nclass Solution {\npublic:\n    int findComplement(int num) {\n        if (num == 0) return 1;\n        \n        unsigned int mask = ~0;\n        \n        while (num & mask) {\n            mask <<= 1;\n        }\n        \n        return ~mask & ~num;\n    }\n};\n\n```\n```javascript []\nvar findComplement = function(num) {\n    if (num === 0) return 1;\n\n    const bitLength = num.toString(2).length;\n    \n    const mask = (1 << bitLength) - 1;\n    \n    return num ^ mask;\n};\n\n```\n```java []\nclass Solution {\n    public int findComplement(int num) {\n        if (num == 0) return 1;\n\n        int bitLength = Integer.toBinaryString(num).length();\n        \n        int mask = (1 << bitLength) - 1;\n        \n        return num ^ mask;\n    }\n}\n\n```\n```C# []\npublic class Solution {\n    public int FindComplement(int num) {\n        int bitLength = (int)Math.Log(num, 2) + 1;\n        \n        int mask = (1 << bitLength) - 1;\n        \n        return num ^ mask;\n    }\n}\n\n```\n---\n\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/cd0fa279-92f2-42b6-b572-3a7e27f50eb4_1724288950.7249384.png)\n\n
['Bit Manipulation', 'Python', 'C++', 'Java', 'Python3', 'JavaScript', 'C#']