Leetcode Note: Go - Largest Number After Digit Swaps by Parity

Largest Number After Digit Swaps by Parity - LeetCode
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/

  • Go 言語で取り組んだメモ

回答

Go golang solution - Largest Number After Digit Swaps by Parity - LeetCode
https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/solutions/1934601/go-golang-solution/

func largestInteger(num int) int {
    tmp := []int{}
    odd, even := []int{}, []int{}
    for num != 0 {
        n := num % 10
        if n & 1 == 1 {
            odd = append(odd, n)
        } else {
            even = append(even, n)
        }
        tmp = append([]int{ n }, tmp...)
        num /= 10
    }
    sort.Ints(odd)
    sort.Ints(even)
    ans := 0
    i, j := len(odd) - 1, len(even) - 1
    for _, v := range tmp {
        if v % 2 == 0 {
            ans = ans * 10 + even[j]
            j--
        } else {
            ans = ans * 10 + odd[i]
            i--
        }
    }
    return ans
}