LeetCode 3309: Maximum Possible Number by Binary Concatenation Solution
Master LeetCode problem 3309 (Maximum Possible Number by Binary Concatenation), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3309. Maximum Possible Number by Binary Concatenation
Problem Explanation
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. :
Solution Code
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);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3309 (Maximum Possible Number by Binary Concatenation)?
This page provides optimized solutions for LeetCode problem 3309 (Maximum Possible Number by Binary Concatenation) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3309 (Maximum Possible Number by Binary Concatenation)?
The time complexity for LeetCode 3309 (Maximum Possible Number by Binary Concatenation) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3309 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3309 in Java, C++, or Python.