memostack
article thumbnail
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
반응형
문제의 저작권은 백준 알고리즘(https://www.acmicpc.net/)에 있습니다

문제

 

풀이

const d = (n) => {
    const answer = [n];
    let t = n;
    while (t > 0) {
        answer.push(t % 10);
        t = parseInt(t / 10);
    }
    return answer.reduce((acc, n) => acc + n, 0);
};

const solution = () => {
    const checkSelfNum = [...Array(10001).keys()].map((_) => true);
    [...Array(10000).keys()].forEach((i) => (checkSelfNum[d(i + 1)] = false));

    return checkSelfNum.reduce((selfNums, isSelfNum, idx) => {
        if (idx !== 0 && isSelfNum) selfNums.push(idx);
        return selfNums;
    }, []);
};

console.log(solution().join('\n'));

 

상세 풀이

자기 자신의 숫자와 각 자리의수를 모두 더하는 d() 함수를 먼저 구현한다.

const d = (n) => {
    const answer = [n];
    let t = n;
    while (t > 0) {
        answer.push(t % 10);
        t = parseInt(t / 10);
    }
    return answer.reduce((acc, n) => acc + n, 0);
};

 

10,001길이의 boolean 값을 담은 리스트를 선언한 뒤에 self number 가 아닌 수를 index로 하여 false로 바꿔준다. 이 과정을 거치면 self number만 true 값으로 남게된다.

(10,000 길이의 배열이 아니라 10,001 길이의 배열을 만든 이유는 index 0을 포함하기 때문)

const solution = () => {
    const checkSelfNum = [...Array(10001).keys()].map((_) => true);
    [...Array(10000).keys()].forEach((i) => (checkSelfNum[d(i + 1)] = false));
    // ...중략...
};

 

iteration을 통해 true 값인 index 값들만 따로 필터링한다.

const solution = () => {
    const checkSelfNum = [...Array(10001).keys()].map((_) => true);
    [...Array(10000).keys()].forEach((i) => (checkSelfNum[d(i + 1)] = false));

    return checkSelfNum.reduce((selfNums, isSelfNum, idx) => {
        if (idx !== 0 && isSelfNum) selfNums.push(idx);
        return selfNums;
    }, []);
};

 

전체 코드

https://github.com/bluemiv/Algorithm/blob/master/baekjoon/nodejs/src/ex04/ex4673.js

 

GitHub - bluemiv/Algorithm: 알고리즘 풀이

알고리즘 풀이. Contribute to bluemiv/Algorithm development by creating an account on GitHub.

github.com

 

 

풀이 결과

문제 풀이 결과

 

관련 글

2022.07.21 - [Algorithm/Beakjoon] - jest 단위테스트를 이용하여 백준 알고리즘 문제 편하게 풀기

 

 

반응형
블로그를 이전하였습니다. 2023년 11월부터 https://bluemiv.tistory.com/에서 블로그를 운영하려고 합니다. 앞으로 해당 블로그의 댓글은 읽지 못할 수 도 있으니 양해바랍니다.
profile

memostack

@bluemiv_mm

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!