3-line / 1-line C++
See my latest update in repo LeetCode\n\n## Solution 1.\n\n\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time:
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1.\n\n```\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time: O(1) as there are at most 32 bits to move\n// Space: O(1)\nclass Solution {\npublic:\n    int findComplement(int num) {\n        unsigned mask = ~0;\n        while (num & mask) mask <<= 1;\n        return ~mask & ~num;\n    }\n};\n```\n\nFor example,\n```\nnum          = 00000101\nmask         = 11111000\n~mask & ~num = 00000010\n```\n\n## Solution 2. \n\n```cpp\n// OJ: https://leetcode.com/problems/number-complement/\n// Author: github.com/lzl124631x\n// Time: O(1)\n// Space: O(1)\nclass Solution {\npublic:\n    int findComplement(int n) {\n        return (unsigned)~0 >> __builtin_clz(n) ^ n;\n    }\n};\n```\n\nFor example:\n\n```\nn                                    = 00000101\n(unsigned)~0 >> __builtin_clz(n)     = 00000111\n(unsigned)~0 >> __builtin_clz(n) ^ n = 00000010\n```\n
[]