728x90

Code

😢 '백준 4673번: 셀프넘버'를 풀었다면 쉽게 풀 수 있는 문제
😊 브루트 포스로 1부터 생성자가 있는 숫자들을 구해주고( d(n) ), N의 생성자가 여러 개라면 배열에 넣어준다.
최종적으로 생성자가 있다면 Math.min을 이용해 최솟값을 출력해주고, 없다면 0을 출력해주면 된다.
각 자릿수를 합하는 것은 위의 셀프넘버를 참고하면 된다.
참고로, 속도는 while로 자릿수를 나누는 게 더 빠르다(Full Code의 2nd Solution code 참고)
Full Code (https://github.com/DasolPark/Dasol_JS_Algorithm/tree/master/Baekjoon)
| // Sum of break up(분해합) |
| // 1st Solution |
| // For submit |
| // const fs = require('fs'); |
| // const input = parseInt(fs.readFileSync('/dev/stdin').toString().trim()); |
| // For local test |
| const input = 216; |
| const constructorArr = []; |
| function d(n) { |
| const N = n.toString().split(''); |
| return n + N.reduce((acc, num) => (acc += parseInt(num)), 0); |
| } |
| for (let i = 1; i <= input; i++) { |
| if (d(i) === input) { |
| constructorArr.push(i); |
| } |
| } |
| if (constructorArr.length) { |
| console.log(Math.min.apply(null, constructorArr)); |
| } else { |
| console.log(0); |
| } |
| // 2nd Solution |
| // For submit |
| // const fs = require('fs'); |
| // const input = parseInt(fs.readFileSync('/dev/stdin').toString().trim()); |
| // For local test |
| // const input = 216; |
| // const constructorArr = []; |
| // function d(n) { |
| // let temp = n; |
| // let sum = n; |
| // while (temp) { |
| // sum += temp % 10; |
| // temp = parseInt(temp / 10); |
| // } |
| // return sum; |
| // } |
| // for (let i = 1; i <= input; i++) { |
| // if (d(i) === input) { |
| // constructorArr.push(i); |
| // } |
| // } |
| // if (constructorArr.length) { |
| // console.log(Math.min.apply(null, constructorArr)); |
| // } else { |
| // console.log(0); |
| // } |
'Algorithm > JavaScript(Node.js)' 카테고리의 다른 글
| 백준 1436번: 영화감독 숌 Node.js(JavaScript) (0) | 2020.02.14 |
|---|---|
| 백준 1018번: 체스판 다시 칠하기 Node.js(JavaScript) (0) | 2020.02.13 |
| 백준 2798번: 블랙잭 Node.js(JavaScript) (0) | 2020.02.01 |
| 백준 2750번: 수 정렬하기 Node.js(JavaScript) (0) | 2020.01.29 |
| 백준 7568번: 덩치 Node.js(JavaScript) (0) | 2020.01.29 |