🌟 Efficient Solution for "Complement of Base 10 Integer" | C++ | 0ms Beats 100.00% | O(log n)
\n\n---\n\n# Intuition\n\nTo find the complement of an integer, we need to flip all bits in its binary representation. For this, determine the number of bits re
##\n\n---\n\n# **Intuition**\n\nTo find the complement of an integer, we need to flip all bits in its binary representation. For this, determine the number of bits required to represent the integer, create a bitmask with all bits set to 1 for this length, and then apply a bitwise XOR operation with the integer to get its complement.\n\n# **Approach**\n\nTo compute the complement of an integer **n**, first determine the number of bits required to represent **n** in binary. Create a **bitmask** with all bits set to 1 by shifting 1 left by the number of bits and then subtracting 1. Finally, use bitwise XOR between **n** and the **bitmask** to obtain the complement. This method is efficient with time complexity **O(log n)** and space complexity **O(1)**.\n\n# **Complexity**\n\n- **Time Complexity** $$O(\\log n)$$ The operations are proportional to the number of bits in the integer, which is $$\\log_2 n$$.\n- **Space Complexity** $$O(1)$$ The algorithm uses a constant amount of extra space for variables.\n# **Code**\n\n```cpp\nclass Solution {\npublic:\n    int bitwiseComplement(int n) {\n        if (n == 0) return 1;  \n        int bitmask{1}, temp{n};\n        while (temp > 0) {\n            bitmask <<= 1;\n            temp >>= 1;\n        }\n        bitmask -= 1;\n        return bitmask ^ n;\n    }\n};\n```\n\n---\n\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A**\n\n---\n\n\n---
['C++']