본문 바로가기

Algorithm

6. 자리 수 더하기 (LV.1)

💫 내가 작성한 코드

 

function solution(n) {
    let nums = [];
    do {
        nums.push(n%10);
        n = Math.floor(n/10);
    } while (n>0);
    const arr = nums;
    const answer = arr.reduce(
    (accumulator, currentValue) => accumulator + currentValue,0);
    return answer;
}

 

 

💫 Review

 

split 메서드 써서 배열 만들고 forEach 로 각각 인자 돌리면 쉽게 풀릴 것 같았지만,

 

1. split 메서드는 느리다고 한다. 

 

2. reduce 메서드에 익숙해지고 싶었다 

 

2가지 이유 때문에 위와 같이 코드를 작성했다. 

 

 

💫 풀이 

 

do...while문을 이용하여 배열 만들기

 

// n= 987
nums.push(987 % 10) = 98...7
n = Math.floor(987 / 10) === 98

// n = 98
nums.push(98 % 10) = 9 ... 8
n = Math.floor(98 / 10) === 9 

// n = 9
nums.push(9 % 10) = 0 ... 9
n = Math.floor(9 / 10) === 0 

// while문 종료

 

 

'Algorithm' 카테고리의 다른 글