๐Ÿค ์€์ง€log ๐Ÿค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค:Javascript] n๋ณด๋‹ค ์ปค์งˆ ๋•Œ๊นŒ์ง€ ๋”ํ•˜๊ธฐ ๋ณธ๋ฌธ

๐ŸŒˆ ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค:Javascript] n๋ณด๋‹ค ์ปค์งˆ ๋•Œ๊นŒ์ง€ ๋”ํ•˜๊ธฐ

Eun_zii 2024. 3. 11. 16:58

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

- n๋ณด๋‹ค ์ปค์งˆ ๋•Œ๊นŒ์ง€ ๋”ํ•˜๊ธฐ

 

๐Ÿ’š ๋ฌธ์ œ์„ค๋ช…

  • ์ •์ˆ˜ ๋ฐฐ์—ด numbers์™€ ์ •์ˆ˜ n์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์˜ ์›์†Œ๋ฅผ ์•ž์—์„œ๋ถ€ํ„ฐ ํ•˜๋‚˜์”ฉ ๋”ํ•˜๋‹ค๊ฐ€ ๊ทธ ํ•ฉ์ด n๋ณด๋‹ค ์ปค์ง€๋Š” ์ˆœ๊ฐ„ ์ด๋•Œ๊นŒ์ง€ ๋”ํ–ˆ๋˜ ์›์†Œ๋“ค์˜ ํ•ฉ์„ return ํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด ์ฃผ์„ธ์š”.

 

๐Ÿ’š ์ œํ•œ์กฐ๊ฑด

  • 1 ≤ numbers์˜ ๊ธธ์ด ≤ 100
  • 1 ≤ numbers์˜ ์›์†Œ ≤ 100
  • 0 ≤ n < numbers์˜ ๋ชจ๋“  ์›์†Œ์˜ ํ•ฉ

 

๐Ÿ’š ํ’€์ด

function solution(numbers, n) {
    let answer = 0;
    for (let i = 0; i < numbers.length; i++) {
         answer += numbers[i];
        if (answer > n) {
            return answer;
        }
    }
}

 

โœ… 

reduce( )๋ฅผ ์‚ฌ์šฉํ•ด์•ผํ•˜๋‚˜ ์‹ถ์—ˆ๋Š”๋ฐ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ํ•˜๋Š”๊ฒŒ ๋” ์‰ฌ์šธ๊ฒƒ ๊ฐ™์•˜๋‹ค.

numbers๋ฅผ ๋ฐ˜๋ณตํ•˜๋ฉด์„œ ๊ฐ ์›์†Œ๋“ค์„ ๋”ํ•ด์ฃผ๋‹ค๊ฐ€ n ๋ณด๋‹ค ์ปค์ง€๋ฉด ์ง์ „๊นŒ์ง€ ๋”ํ•œ๊ฐ’์„ returnํ•ด์ค€๋‹ค.

 

๐Ÿ’ก ๋‹ค๋ฅธ์‚ฌ๋žŒ ํ’€์ด

function solution(numbers, n) {
    return numbers.reduce((a,c,i,t)=>(a<=n)?a+c:a)
}

 

728x90