Simple Java Code ☠️
\n# Code\njava []\nclass Solution {\n    public int findComplement(int num) {\n        String str = Integer.toBinaryString(num);\n        String res = "";\n    
\n# Code\n```java []\nclass Solution {\n    public int findComplement(int num) {\n        String str = Integer.toBinaryString(num);\n        String res = "";\n        for(int i=0;i<str.length();i++){\n            if(str.charAt(i) == \'0\'){\n                res += \'1\';\n            }\n            else{\n                res += \'0\';\n            }\n        }\n        return Integer.parseInt(res,2);\n    }\n}\n```\n\n### Explanation\n\nThis code is a solution to find the complement of an integer. The complement is obtained by flipping all the 0\'s to 1\'s and all the 1\'s to 0\'s in the binary representation of the integer.\n\n### Step-by-Step Logic:\n\n1. **Convert Integer to Binary String**:\n   ```java\n   String str = Integer.toBinaryString(num);\n   ```\n   - The method `Integer.toBinaryString(num)` converts the integer `num` into its binary string representation. For example, if `num = 5`, `str` would be `"101"`.\n\n2. **Flip the Binary Digits**:\n   ```java\n   String res = "";\n   for(int i=0;i<str.length();i++){\n       if(str.charAt(i) == \'0\'){\n           res += \'1\';\n       }\n       else{\n           res += \'0\';\n       }\n   }\n   ```\n   - Here, the code iterates over each character in the binary string `str`.\n   - For each character:\n     - If the character is `\'0\'`, it appends `\'1\'` to the result string `res`.\n     - If the character is `\'1\'`, it appends `\'0\'` to `res`.\n   - This effectively flips all the bits of the binary string.\n\n   For example, if `str = "101"`, after flipping, `res` would be `"010"`.\n\n3. **Convert the Resultant Binary String Back to Integer**:\n   ```java\n   return Integer.parseInt(res,2);\n   ```\n   - Finally, the method `Integer.parseInt(res, 2)` converts the binary string `res` back to an integer. The second argument `2` specifies that the string is in base 2 (binary).\n   - For example, `"010"` is converted back to the integer `2`.\n\n### Example:\n- Suppose `num = 5`. The binary representation of `5` is `"101"`.\n- The flipped binary string becomes `"010"`, which corresponds to the integer `2`.\n- Therefore, the method returns `2` as the complement of `5`.\n\n### Complexity:\n- **Time Complexity**: The time complexity is `O(n)`, where `n` is the number of bits in the binary representation of the integer. This is because the code iterates over each bit once.\n- **Space Complexity**: The space complexity is also `O(n)` due to the storage of the binary string and its complement.\n\n\n\n
['String', 'Java']