|
1 | 1 | const fs = require("fs"); |
2 | | -const inputData = fs |
| 2 | +const input = fs |
3 | 3 | .readFileSync("./input.txt", "utf8") |
4 | 4 | // .readFileSync("/dev/stdin", "utf8") |
5 | 5 | .toString() |
6 | 6 | .trim(); |
7 | 7 |
|
8 | | -function solution(inputData) { |
9 | | - const num = inputData.split(""); |
10 | | - const soltResult = num.sort((a, b) => b - a).join(""); |
| 8 | +function solution(input) { |
| 9 | + // 숫자 배열화 |
| 10 | + const numArr = input.split(""); |
11 | 11 |
|
12 | | - return soltResult === inputData ? "0" : soltResult; |
| 12 | + // 뒤에서 부터 감소하는 index 찾기 |
| 13 | + let index = numArr.length - 2; |
| 14 | + while (index >= 0 && numArr[index] >= numArr[index + 1]) { |
| 15 | + index--; |
| 16 | + } |
| 17 | + |
| 18 | + // 만약 감소하는 부분이 없다면 0을 반환 |
| 19 | + if (index < 0) return 0; |
| 20 | + |
| 21 | + // numArr[index] 보단 크고 가장 뒤에있는 값 j에 저장 |
| 22 | + let j = numArr.length - 1; |
| 23 | + while (numArr[index] >= numArr[j]) { |
| 24 | + j--; |
| 25 | + } |
| 26 | + |
| 27 | + // 만약 numArr[index]보다 큰 값이 없다면 0을 반환 |
| 28 | + if (j < 0) return 0; |
| 29 | + |
| 30 | + // 두 숫자 자리 바꾸기 |
| 31 | + [numArr[index], numArr[j]] = [numArr[j], numArr[index]]; |
| 32 | + |
| 33 | + // numArr[index] 뒤의 내용 자르고 reverse |
| 34 | + const sliceReversed = numArr.slice(index + 1).reverse(); |
| 35 | + |
| 36 | + // 자른 부분 붙히기 |
| 37 | + numArr.splice(index + 1, sliceReversed.length, ...sliceReversed); |
| 38 | + |
| 39 | + // 최종 배열 숫자화 |
| 40 | + return numArr.join(""); |
13 | 41 | } |
14 | 42 |
|
15 | | -console.log(solution(inputData)); |
| 43 | +console.log(solution(input)); |
0 commit comments