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()
으로 다 쪼개서 더함.