carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode2231: Largest Number After Digit Swaps by Parity #363

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

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.

Example 1:

Input: num = 1234 Output: 3412 Explanation: Swap the digit 3 with the digit 1, this results in the number 3214. Swap the digit 2 with the digit 4, this results in the number 3412. Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number. Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.

Example 2:

Input: num = 65875 Output: 87655 Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. Swap the first digit 5 with the digit 7, this results in the number 87655. Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.

Constraints:

1 <= num <= 109

carloscn commented 1 year ago

Analysis

static int32_t largest_integer(int32_t num)
{
    int32_t ret = 0;
    int32_t rom[32] = {0};

    if (num == 0) {
        goto finish;
    }

    size_t i = 0;
    while (num != 0) {
        rom[i] = num % 10;
        num /= 10;
        i ++;
    }

    for (size_t j = 0; j < i; j ++) {
        for (size_t k = j + 1; k < i; k ++) {
            if (((rom[j] & 0x1) == (rom[k] & 0x1)) &&
                (rom[k] < rom[j])) {
                utils_swap_int32(rom + k, rom + j);
                break;
            }
        }
        int32_t e = 1;
        for (size_t m = 0; m < j; m ++) {
            e *= 10;
        }
        ret += e * rom[j];
    }

finish:
    return ret;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1169889 https://github.com/carloscn/structstudy/commit/20da4117c72304e3c1825e5138c0c6383a09dab1