Easy and Simple C++ Approach ✅ | Beginner Friendly 🔥🔥🔥
Intuition\nTo find the bitwise complement of a number n, we need to flip all the bits of n. For example, if n is 5 (binary 101), its bitwise complement should b
# Intuition\nTo find the bitwise complement of a number `n`, we need to flip all the bits of `n`. For example, if `n` is `5` (binary `101`), its bitwise complement should be `2` (binary `010`).\n\n# Approach\n1. If `n` is `0`, directly return `1` because the complement of `0` is `1`.\n1. Create a mask that has the same number of bits as `n` but all set to `1`.\n1. XOR `n` with this mask to get the bitwise complement.\n\n# Detailed Steps:\n- Initialize `mask` to `0`.\n- If `n` is `0`, return `1`.\n- Copy `n` to `m`.\n- Create the mask by left shifting `mask` and OR\'ing it with `1` until `m` becomes `0`.\n- XOR `n` with `mask` to get the result.\n\n# Complexity\n- Time complexity: O(logn)\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`Upvote! It only takes 1 click\uD83D\uDE09`\n# Code\n```\nclass Solution {\npublic:\n    int bitwiseComplement(int n) {\n        int m = n ;\n        int mask = 0;\n        if (n == 0)\n        return 1;\n\n        while(m!=0){\n            mask = (mask<<1)|1;\n            m=(m>>1);\n        }\n        int ans = n^mask;\n        //or ans = (~n) & mask;\n        return ans;\n\n    }\n};\n```\n![upvote.jpeg](https://assets.leetcode.com/users/images/48b755ae-c41b-474d-966e-aa5674e41ff4_1720943081.9620614.jpeg)
['Bit Manipulation', 'C++']