CodeWars 코딩 문제 2021/04/23 - Twisted Sum

이호현·2021년 4월 23일
0

Algorithm

목록 보기
110/138

[문제]

Find the sum of the digits of all the numbers from 1 to N (both ends included).

Examples

N = 4

1 + 2 + 3 + 4 = 10

N = 10

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) = 46

N = 12

1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + (1 + 0) + (1 + 1) + (1 + 2) = 51

(요약) 1부터 n까지 더하는데 자릿수가 2자리 이상이면 다 쪼개서 1의 자리로 만들어서 더해라.

[풀이]

function twistedSum(n) {
  let answer = 0;

  for(let i = 1; i <= n; i++) {
    if(i < 10) {
      answer += i;
    }
    else {
      `${i}`.split('').forEach(str => answer += (str * 1));
    }
  }

  return answer;
}

1부터 n까지 반복문을 돌리면서 2자리 이상일 때 split()으로 다 쪼개서 더함.

profile
평생 개발자로 살고싶습니다

0개의 댓글