3309. Maximum Possible Number by Binary Concatenation
Explanation:
To solve this problem, we need to concatenate the binary representations of the given numbers in a way that maximizes the resulting number. This can be achieved by sorting the numbers in descending order based on the number of set bits in their binary representation. We then concatenate these numbers in the sorted order to form the maximum possible number.
- Convert each number in the input array to its binary representation.
- Sort the numbers based on the count of set bits in their binary representation in descending order.
- Concatenate the binary representations of the sorted numbers to form the maximum possible number.
- Convert the concatenated binary number back to decimal form. :
import java.util.Arrays;
class Solution {
public int getMaxNum(int[] nums) {
String[] binaryNums = new String[nums.length];
for (int i = 0; i < nums.length; i++) {
binaryNums[i] = Integer.toBinaryString(nums[i]);
}
Arrays.sort(binaryNums, (a, b) -> Integer.bitCount(Integer.parseInt(b)) - Integer.bitCount(Integer.parseInt(a)));
StringBuilder sb = new StringBuilder();
for (String num : binaryNums) {
sb.append(num);
}
return Integer.parseInt(sb.toString(), 2);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.