Problem Solution/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/JS] ์ž๋ฆฟ์ˆ˜ ๋”ํ•˜๊ธฐ

yuri lee 2023. 9. 5. 20:34
๋ฐ˜์‘ํ˜•

Problem Description

์ •์ˆ˜ ๋ฐฐ์—ด numbers๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์˜ ๊ฐ ์›์†Œ์— ๋‘๋ฐฐํ•œ ์›์†Œ๋ฅผ ๊ฐ€์ง„ ๋ฐฐ์—ด์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.์ •์ˆ˜ n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ n์˜ ๊ฐ ์ž๋ฆฌ ์ˆซ์ž์˜ ํ•ฉ์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”

 

Restrictions

  • 0 ≤ n ≤ 1,000,000

 

Input/Output Example

  • ์ž…์ถœ๋ ฅ ์˜ˆ #1 1 + 2 + 3 + 4 = 10์„ returnํ•ฉ๋‹ˆ๋‹ค.
  • ์ž…์ถœ๋ ฅ ์˜ˆ #2 9 + 3 + 0 + 2 + 1 + 1 = 16์„ returnํ•ฉ๋‹ˆ๋‹ค.

 

My solution

function solution(n) {
    let result = 0
    let i;
    for (i = 0; i < (n.toString()).length; i++) {
      result += parseInt(n.toString()[i])
    }
    return result
}

 

Another solutions

function solution(n) {
  return n
    .toString()
    .split("")
    .reduce((acc, cur) => acc + Number(cur), 0);
}

split๊ณผ reduce๋ฅผ ์‚ฌ์šฉํ•ด์„œ๋„ ํ•  ์ˆ˜ ์žˆ๊ตฐ์š”..! 

 


https://school.programmers.co.kr/learn/courses/30/lessons/120906

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

๋ฐ˜์‘ํ˜•