๐งฎ
Sum of Digits
Sum of Digits์ฌ์ ์๊ณ ๋ฆฌ์ฆ +10pts
Problem
Write a function that returns the sum of all digits in a number.
Examples
Input:
sumDigits(123)Output:
6๐ก 1 + 2 + 3 = 6
Explanation
์ด ๋ฌธ์ ๋ **๋ฌธ์์ด ๋ณํ๊ณผ reduce**๋ฅผ ์กฐํฉํ์ฌ ์๋ฆฟ์ ํฉ์ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ ํ์ตํฉ๋๋ค. ## ํต์ฌ ๊ฐ๋ : ์๋ฆฟ์ ๋ถ๋ฆฌ ์ซ์๋ฅผ ๋ฌธ์์ด๋ก ๋ณํํ์ฌ ๊ฐ ์๋ฆฟ์์ ์ ๊ทผํฉ๋๋ค. ### ์ ๊ทผ ๋ฐฉ๋ฒ ```javascript Math.abs(n).toString().split('').reduce((sum, d) => sum + Number(d), 0) ``` ### ๋จ๊ณ๋ณ ๋ถ์ 1. Math.abs(n): ์์ ์ฒ๋ฆฌ 2. toString(): ์ซ์ โ ๋ฌธ์์ด 3. split(''): ๊ฐ ์๋ฆฟ์ ๋ถ๋ฆฌ 4. reduce: ํฉ๊ณ ๊ณ์ฐ ...
View detailed explanation โKey Concepts
๋ฌธ์์ด ๋ณํ reduce ์๋ฆฟ์ ํฉ Math.abs
Time: O(log n) Space: O(log n)
solution.js
Ctrl + Enter
Run tests to see results here.