You are given a positive integer num
. You may swap any two digits of num
that have the same parity (i.e. both odd digits or both even digits).
Return the largest possible value of num
after any number of swaps.
LeetCode Problem - 2231
class Solution {
public int largestInteger(int num) {
// Convert the number to a string to extract its digits.
String numString = Integer.toString(num);
// Array to hold the digits of the number.
int[] numArray = new int[numString.length()];
// Extract the digits of the number and store them in the array.
for (int i=0; i<numString.length(); i++){
numArray[i] = Character.getNumericValue(numString.charAt(i));
}
// Iterate through the digits of the number to rearrange them for the largest integer.
for (int i=0; i<(numArray.length); i++){
// Initialize the maximum digit as the current digit.
int max = numArray[i];
// If the current digit is odd.
if (numArray[i]%2 != 0){
// Find the largest odd digit from the remaining digits.
for (int j=i+1; j<numArray.length; j++){
if (numArray[j]%2 != 0 && numArray[j]>max){
// Swap the current digit with the largest odd digit found.
max = numArray[j];
int temp = numArray[i];
numArray[i] = numArray[j];
numArray[j] = temp;
}
}
}
// If the current digit is even.
else {
// Find the largest even digit from the remaining digits.
for (int k=i+1; k<numArray.length; k++){
if (numArray[k]%2==0 && numArray[k]>max){
// Swap the current digit with the largest even digit found.
max = numArray[k];
int temp = numArray[i];
numArray[i] = numArray[k];
numArray[k] = temp;
}
}
}
}
// Reconstruct the rearranged number from the array of digits.
int result = 0;
for (int e:numArray){
result = result*10+e;
}
// Return the largest possible integer.
return result;
}
}