Largest Number After Digit Swaps by Parity - Problem
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 performing any number of such swaps.
Note: Digits with the same parity can be rearranged in any order to maximize the number.
Input & Output
Example 1 — Basic Case
$
Input:
num = 1234
›
Output:
3412
💡 Note:
Odd digits [1,3] sorted descending become [3,1], even digits [2,4] sorted descending become [4,2]. Maintaining original positions: 3412
Example 2 — Same Parity Only
$
Input:
num = 65875
›
Output:
87655
💡 Note:
Odd digits [5,7,5] sorted descending: [7,5,5]. Even digits [6,8] sorted: [8,6]. Result: 87655
Example 3 — Already Optimal
$
Input:
num = 247
›
Output:
427
💡 Note:
Even digits [2,4] become [4,2], odd digit [7] stays. Result: 427
Constraints
- 1 ≤ num ≤ 109
- num consists of digits only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code