✅Easy C++ Solution with Video Explanation✅
Video Explanation\nhttps://youtu.be/1X7p3EDVrks?si=X1WTUiktBZ3sARbO\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requ
# Video Explanation\nhttps://youtu.be/1X7p3EDVrks?si=X1WTUiktBZ3sARbO\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the complement of a number in its binary form, which involves flipping all the bits (i.e., turning 0s into 1s and 1s into 0s). To achieve this, we need to isolate the bits of the number that are relevant (i.e., the bits that represent the number) and flip only those.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Edge Case Handling:** If num is 0, its complement is 1 because flipping no bits (since there are no 1s) effectively gives us 1. This is handled with a simple conditional check at the start.\n2. **Bitmask Initialization:** We start with a bitmask that has all bits set to 1. The bitmask is created using ~0, which results in a value where all bits are 1 in binary.\n3. **Shifting the Bitmask:** The goal is to shift the bitmask left until it aligns with the number of bits used by num. We repeatedly shift the bitmask left until num & bitmask results in 0. This ensures that the bitmask has zeroes in the positions corresponding to the significant bits of num.\n4.** Flipping Bits:** Once the bitmask is correctly aligned, we flip the bits of num using the XOR operation with ~bitmask. The ~bitmask has 1s only in positions where num has significant bits, so the XOR operation flips only these bits, leaving the rest unchanged.\n5. **Return the Result:** The XOR result is the complement of num, which is returned as the final answer.\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```cpp []\nclass Solution {\npublic:\n    int findComplement(int num) {\n        if (num == 0) return 1; \n\n        unsigned int bitmask = ~0; \n        \n        \n        while (num & bitmask) {\n            bitmask <<= 1;\n        }\n\n      \n        return num ^ ~bitmask;\n    }\n};\n\n```
['C++']