728x90

Code

😢 쉬운 문제였기 때문에 금방 풀었으나, 문제는 뜻밖의 부분에 있었다.
값을 읽어올 때, trim()을 적용시켜주지 않아서, 마지막 공백 ''이 들어왔기 때문이다.
그래서 ''%42=0이 되어버렸고, theRestMap Object key값 0의 값이 1만큼 올라갔다.
따라서, 결과값이 항상 1만큼 더 높게 나와 '틀렸습니다' 결과를 받았다.
😊 Object를 하나 선언해주고, for of loop을 이용해 해당 나머지값(key)이 중복될 때마다 값(value)를 1씩 증가해준다.
그런 후 마지막에 Object.keys(theRestMap).length 를 출력하여 key의 개수(길이)만큼 출력하면 그것이 나머지의 개수다.
Full Code
| // 2nd Solution |
| // For submit |
| // const fs = require('fs'); |
| // const input = fs |
| // .readFileSync('/dev/stdin') |
| // .toString() |
| // .trim() |
| // .split('\n'); |
| // For local test |
| const input = ['39', '40', '41', '42', '43', '44', '82', '83', '84', '85']; |
| const Rest = []; |
| let counter = 0; |
| for (let i = 0; i < input.length; i++) { |
| const RestNum = parseInt(input[i]) % 42; |
| if (!Rest[RestNum]) { |
| Rest[RestNum] = 1; |
| counter++; |
| } |
| } |
| console.log(counter); |
| // 1st Solution ( Wrong but this is correct in local) |
| // 아마 Object.keys가 적용되지 않는 듯? 인줄 알았으나 값을 가져오는 과정에 trim()을 추가하니 해결 되었다. |
| // For submit |
| // const fs = require('fs'); |
| // const input = fs.readFileSync('/dev/stdin').toString().split('\n'); |
| // For local test |
| // const input = ['39', '40', '41', '42', '43', '44', '82', '83', '84', '85']; |
| // const theRestMap = {}; |
| // for (let num of input) { |
| // const theRest = num % 42; |
| // theRestMap[theRest] = theRestMap[theRest] ? theRestMap[theRest] + 1 : 1; |
| // } |
| // console.log(Object.keys(theRestMap).length); |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
| Reverse String(문자열 거꾸로 바꾸기) Node.js(JavaScript) (0) | 2019.12.23 |
|---|---|
| 백준 1546번: 평균(New average) Node.js(JavaScript) (0) | 2019.12.22 |
| 백준 2577번: 숫자의 개수(The number of numbers) Node.js(JavaScript) (0) | 2019.12.20 |
| 백준 2920번: 음계(scale) Node.js(JavaScript) (0) | 2019.12.20 |
| 백준 2562번: 최댓값(Max and Index of max) Node.js(JavaScript) (0) | 2019.12.20 |