C++ EASY TO SOLVE || Different Variations of code with detailed exaplanations
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.\n\nIntuition:-\nThere is not m
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.\n\n**Intuition:-**\nThere is not much of a intuition in this question as the question is loud and clear about it\'s use of bit manipulation .\n\nTo make things a bit more interesting let\'s do this question with and wihout bit manipulation\n\n* **Using Bit Manipulations:---**\n\n**Bit masking can be summarized with this image (^_^)**\n![image](https://assets.leetcode.com/users/images/d478c8d2-3fbb-49fd-956a-ae31a014a926_1640579005.4899502.jpeg) \nThus, we can conclude that masking means to keep/change/remove a desired part of information.\n\n**Dry run of bitmasking:-**\n![image](https://assets.leetcode.com/users/images/face3402-7526-4282-becd-7564dc8b4a95_1640574890.4955626.png)\n\n**Code1[Using bitmasking]:-**\n```\nclass Solution {\npublic:\n    int findComplement(int num) {\n        unsigned mask = ~0;\n        while( mask & num ) mask = mask << 1;\n        return ~num ^ mask;\n    }\n};\n```\n**Time Complexity:** *`O(log(num)) = O(since we will be moving at most 32bits only) = O(1)`*\n**Space Complexity:** *`O(1)`*\n\n**Code2[Using xor]:-**\nBasic idea is to find the smallest power of 2 that is larger than the `input number num`, and output the difference between `powerof2s` and `num` . \n\n**Dry run:-**\n```\nFor example let\'s the example from description of the question:-\nInput: num = 5(101) ,\nThus the smallest power of 2 (and larger than 5) is 8 (1000)\nThe output should be 8 - 5 - 1 = 2 (010).\n```\n\n```\nclass Solution {\npublic:\n    int findComplement(int num) {\n        long powerof2s = 2, temp = num;\n        \n        while(temp>>1) {\n            temp >>= 1;\n            powerof2s <<= 1;\n        }\n        \n        return powerof2s - num - 1;\n    }\n};\n```\n.\n\n* **Without using Bit manipulation:-**\n\n***Code:-***\n```\nclass Solution {\npublic:\n    int findComplement(int num) {\n        vector<int> temp; \n\t\t// convert to binary representation\n        while( num != 0 ){\n            temp.push_back( num % 2 );\n            num /= 2;\n        } \n\t\t// make complement\n        for(int i=0; i<temp.size(); i++){\n            if( temp[i] == 1 ) temp[i] = 0;\n            else if( temp[i] == 0 ) temp[i] = 1;\n        } int res = 0;\n        for(int i=temp.size()-1; i>-1; i--) res = res * 2 + temp[i];\n        return res;\n    }\n};\n```\n\n
['Bit Manipulation', 'C', 'C++']