The problem involves rearranging the digits of a number such that the resulting number is the largest possible while maintaining the parity of each digit. Parity means:
The solution involves separating the digits by parity, sorting them in descending order, and reconstructing the number.
class Solution {
public int largestInteger(int num) {
// Convert the number to a character array
char[] digits = String.valueOf(num).toCharArray();
// Separate even and odd digits
List<Integer> evens = new ArrayList<>();
List<Integer> odds = new ArrayList<>();
for (char digit : digits) {
int d = digit - '0';
if (d % 2 == 0) {
evens.add(d);
} else {
odds.add(d);
}
}
// Sort even and odd digits in descending order
evens.sort(Collections.reverseOrder());
odds.sort(Collections.reverseOrder());
// Reconstruct the largest number
StringBuilder result = new StringBuilder();
int evenIndex = 0, oddIndex = 0;
for (char digit : digits) {
int d = digit - '0';
if (d % 2 == 0) {
result.append(evens.get(evenIndex++));
} else {
result.append(odds.get(oddIndex++));
}
}
return Integer.parseInt(result.toString());
}
}
O(n)
โ Iterating through the digits of the number.O(n log n)
โ Sorting the even and odd digits.O(n)
โ Rebuilding the number from the sorted digits.O(n log n)
.Input: num = 65875
Output: 87655
Explanation:
- Even digits: [6, 8]
- Odd digits: [5, 7, 5]
- Rearrange evens: [8, 6]
- Rearrange odds: [7, 5, 5]
- Reconstruct: 87655