1.문제
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:
2.풀이
- 숫자를 배열로 바꾼다음 짝수와 홀수 따로 분리해서 저장하면서 인덱스도 따로 저장을 해둔다.
- 각각 배열을 내림차순 정렬한다.
- 인덱스 배열의 인덱스 값 순으로 다시 재배치 하여 리턴한다.
/**
* @param {number} num
* @return {number}
*/
const largestInteger = function (num) {
num = String(num).split("");
const odd = [];
const even = [];
const oddIndex = [];
const evenIndex = [];
const result = [];
for (let i = 0; i < num.length; i++) {
// 짝수 숫자와 홀수 숫자를 나누어서 숫자와 인덱스 값을 배열에 저장
if (parseInt(num[i]) % 2 === 0) {
even.push(parseInt(num[i]));
evenIndex.push(i);
} else {
odd.push(parseInt(num[i]));
oddIndex.push(i);
}
}
odd.sort((a, b) => b - a); // 내림차순 정렬
even.sort((a, b) => b - a);
for (let i = 0; i < evenIndex.length; i++) {
// 저장해둔 인덱스 순으로 result 배열에 넣어준다.
result[evenIndex[i]] = even[i];
}
for (let i = 0; i < oddIndex.length; i++) {
result[oddIndex[i]] = odd[i];
}
return result.join("");
};
3.결과
