[C++] Simple Bitwise Solution Explained, 100% Time, ~25% Space
A rather simple problem to tackle and the way to do it is rather straightforward itself, where you might just decide to do things differently mostly in terms of
A rather simple problem to tackle and the way to do it is rather straightforward itself, where you might just decide to do things differently mostly in terms of which bitwise trick to employ or not here.\n\nTo solve this challenge, I first of all created 2 support variables:\n* `res` to store our own result;\n* `i` to store the current power of 2 we are working with.\n\nWe are going to loop until we reach `n == 0` and please note that this approach is more efficient than a few others, constantly using 31 bits even for smaller numbers.\n\nAlso notice that we are using a `do`... `while` loop, since we want it to run at least once, in order to handle the edge case when we initially already have `n == 0`.\n\nInside the loop we will keep shaving off the right most (ie: less significant) bit with `2 & 1`, then reverse it with `^ 1` (althought you might just go for other tricks here, like using boolean negation: `!(n % 2)`, for example) and finally we multiply it by the current power of 2 we are treating at the moment.\n\nAfter that, we prepare the ground for the next iteration, specularly multiplying `i` by `2` (with the shift assignment operator `<<=`, because bitwise!) and dividing `n` by `2`.\n\nOnce we are done looping, time to return `res` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n    int bitwiseComplement(int n) {\n        // support variables\n        int res = 0, i = 1;\n        // shaving off the least significant bit from n and adding its complement to res\n        do {\n            // updating res\n\t\t\tres += ((n & 1) ^ 1) * i;\n            // preparing for the next iteration\n\t\t\ti <<= 1;\n            n >>= 1;\n        } while (n);\n        return res;\n    }\n};\n```
['Bit Manipulation', 'C', 'C++']