Beginner Friendly Python || Beats 91%
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nLet\'s assume a number,
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s assume a number, say 10. \n\n```\nBinary version = 1010\nComplement = 0101\nInteger compelement = 5\n```\n\n```\nmask is initially 0,\nTill m = 10 (1010) is not 0,\n1. add a 1 (left shift 0 at the end + OR with 1), mask = 1\n2. divide 10 by 2 or right shift by 1\n3. now m = 5(101)\n- Iteration 2: mask = 11, m = 2 (10)\n- Iteration 3: mask = 111, m = 1 (1)\n- Iteration 4: mask = 1111, m = 0\n```\n\n\n\nTo do this using code, we follow these steps:\n\n1. First, we check if the given number is 0. If it is, the complement is 1, because flipping 0 gives us 1.\n```\nif n == 0:\n    return 1\n```\n\n2. To find the complement for any other number, we need to figure out how many bits it has. \n\n\n3. Now, we create a "mask," which is a pattern of bits. We set as many bits as our number has to 1. So, for 10, our mask is \'1111\' (4 ones in binary).\n\n```\nmask is basically all ones. \nfor example: \nmask for 10 (1010) = 1111\nmask for 5 (101) = 111\nmask for 11 (1011) = 1111\n```\n```\nmask is initially 0,\nTill m = 10 (1010) is not 0,\n- add a 1 (left shift 0 at the end + OR with 1), mask = 1\n- divide 10 by 2 or right shift by 1\n- now m = 5(101)\n- Iteration 2: mask = 11, m = 2 (10)\n- Iteration 3: mask = 111, m = 1 (1)\n- Iteration 4: mask = 1111, m = 0\n\n```\n\n4. Take the complement of the original number (flipping the bits using \'~\' in code) and apply the mask to it (using \'&\' in code). This gives us the complement of the number.\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n    def bitwiseComplement(self, n: int) -> int:\n        #generate a new number\n        if n == 0:\n            return 1\n        m = n\n        mask = 0\n        while (m!=0):\n            #generate a mask\n            mask = (mask << 1) | 1\n            m = m >> 1\n        answer = (~n) & mask\n        \n        return answer\n        \n        \n\n        \n        \n```
['Python3']