Input: num =1234Output: 3412Explanation: Swap the digit 3with the digit 1,this results in the number 3214.Swap the digit 2with the digit 4,this results in the number 3412.Note that there may be other sequences of swaps but it can be shown that 3412is the largest possible number.Also note that we may not swap the digit 4with the digit 1 since they are of different parities.
Input: num =65875Output: 87655Explanation: Swap the digit 8with the digit 6,this results in the number 85675.Swap the first digit 5with the digit 7,this results in the number 87655.Note that there may be other sequences of swaps but it can be shown that 87655is the largest possible number.
To get the largest number, sort all odd digits in descending order and all even digits in descending order. Then, for each digit in the original number, replace it with the largest available digit of the same parity.
classSolution {
public:int largestInteger(int num) {
vector<int> odd, even, digits;
int n = num;
while (n) { digits.push_back(n%10); n /=10; }
reverse(digits.begin(), digits.end());
for (int d : digits) (d%2? odd : even).push_back(d);
sort(odd.rbegin(), odd.rend());
sort(even.rbegin(), even.rend());
int oi =0, ei =0, ans =0;
for (int d : digits) {
ans = ans*10+ (d%2? odd[oi++] : even[ei++]);
}
return ans;
}
};
classSolution {
publicintlargestInteger(int num) {
List<Integer> digits =new ArrayList<>();
int n = num;
while (n > 0) { digits.add(0, n%10); n /= 10; }
List<Integer> odd =new ArrayList<>(), even =new ArrayList<>();
for (int d : digits) if (d%2==0) even.add(d); else odd.add(d);
odd.sort(Collections.reverseOrder());
even.sort(Collections.reverseOrder());
int oi = 0, ei = 0, ans = 0;
for (int d : digits) {
ans = ans*10 + (d%2==0 ? even.get(ei++) : odd.get(oi++));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funlargestInteger(num: Int): Int {
val digits = num.toString().map { it - '0' }
val odd = digits.filter { it%2==1 }.sortedDescending().toMutableList()
val even = digits.filter { it%2==0 }.sortedDescending().toMutableList()
val ans = digits.map { if (it%2==0) even.removeAt(0) else odd.removeAt(0) }
return ans.joinToString("") { it.toString() }.toInt()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
deflargestInteger(self, num: int) -> int:
digits = [int(x) for x in str(num)]
odd = sorted([d for d in digits if d%2], reverse=True)
even = sorted([d for d in digits if d%2==0], reverse=True)
oi = ei =0 ans = []
for d in digits:
if d%2:
ans.append(odd[oi])
oi +=1else:
ans.append(even[ei])
ei +=1return int(''.join(map(str, ans)))