C++ | 0 ms | Beats 100%
Intuition\n Describe your first thoughts on how to solve this problem. \nThe code handles the base case where num is 0 by returning 1, as the bitwise complement
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe code handles the base case where num is 0 by returning 1, as the bitwise complement of 0 is 1.\n\nIt iterates through each bit of num to compute its bitwise complement by flipping each bit individually.\n\nIt does this by extracting each bit (0 or 1) of num, flipping it using XOR with 1, and then accumulating the result by shifting it to the appropriate position.\n\nThe process continues until all bits of num are processed, resulting in the complete bitwise complement of num.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Base Case Handling: If num is 0, its bitwise complement is 1. Therefore, the function returns 1 for this case.\n\n2. Bitwise Complement Calculation: The code iterates through each bit of the input number num by continuously dividing num by 2 until it becomes zero. In each iteration:\n\n3. It computes the remainder when num is divided by 2, which gives the least significant bit (LSB) of num.\n    - It flips the LSB using the XOR operator (rem = rem ^ 1), which effectively computes the bitwise complement of the LSB.\n    - It then updates the answer by multiplying the complemented bit (rem) with a multiplier (mul) and adding it to the result (ans).\n    - It updates the multiplier (mul) by doubling it, which effectively shifts it to the left.\n    - Finally, it updates num by integer division (num = num / 2), effectively shifting it to the right.\n\n4. Return Result: After completing the bitwise complement calculation, the function returns the computed result ans.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this approach is O(log n), where n is the value of the input integer num. \n\nThis is because the while loop iterates through the bits of num, and the number of iterations required is proportional to the number of bits in num, which is logarithmic with respect to num.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(1), constant space complexity, as the space used by variables (num, ans, mul, rem) does not depend on the size of the input integer num.\n\n# Code\n```\nclass Solution {\npublic:\n    int bitwiseComplement(int num) {\n        if(num==0) return 1;\n        // if(num==1) return 0;\n        int ans=0;\n        int mul = 1;\n         while(num){\n            int rem = num%2;\n            rem = rem^1;\n            ans = rem*mul + ans;\n            mul = mul*2;\n            num = num/2;\n         }\n         return ans;\n    }\n};\n\n\n```
['C++']