Leetcode Problem 2231. Largest Number After Digit Swaps by Parity

2231. Largest Number After Digit Swaps by Parity

Leetcode Solutions

Sorting Digits by Parity and Reconstructing the Number

  1. Convert the integer num to a string to easily access individual digits.
  2. Create two lists, evens and odds, to store even and odd digits respectively.
  3. Iterate through the digits of the number and add each digit to the corresponding list based on its parity.
  4. Sort both evens and odds lists in descending order.
  5. Initialize an empty list result to store the digits of the final number.
  6. Iterate through the original digits again and for each digit, pop the largest available digit from the corresponding sorted list and append it to result.
  7. Join the digits in result to form a string and convert it back to an integer.
  8. Return the reconstructed integer.
UML Thumbnail

Iterative In-Place Swap with Parity Check

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...