Q. Your task is to make a function that can take any non-negative integer as an argument and return it with its digits in descending order. Essentially, rearrange the digits to create the highest possible number.
S. int - String - List 순서로 형변환 > 오름차순 정렬 > reversed List > join() > int로 형변환했다.
Swift에서는 sort / sorted 가 따로 있고 부등호(>, <)로 오름차순과 내림차순을 간단하게 설정할 수 있다.
또 int(str) 이런 식으로 괄호로 감싸주기만 하면 되기때문에 형변환이 조금 더 간편하다.
int descendingOrder(n) {
List strList = n.toString().split('');
strList.sort();
strList = strList.reversed.toList(); // reversed는 Iterable 타입을 반환
return int.parse(strList.join('')); // int.parse(str): String to int
}
+
compare 함수를 이용해 정렬순서를 반대로 변경할 수도 있다.
int descendingOrder(n) {
List strList = n.toString().split('');
strList.sort((a, b) => b.compareTo(a));
return int.parse(strList.join(''));
}
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Get the Middle Character (0) | 2024.06.04 |
---|---|
[Codewars] Sum of positive (1) | 2024.06.03 |
[Codewars] Return Negative (0) | 2024.06.03 |
[Codewars] Vowel Count (0) | 2024.06.03 |
[Codewars] Even or Odd (0) | 2024.06.03 |