티스토리 뷰

1Day 1Algorithm

[DAY 2] Simple Array Sum

walk_through_me 2019. 10. 2. 18:30

Given an array of integers, find the sum of its elements.

For example, if the array ar=[1, 2, 3],  1 + 2 + 3 = 6, so return 6.

 

Function Description

Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer.

simpleArraySum has the following parameter(s):

  • ar: an array of integers
 

Simple Array Sum | HackerRank

Calculate the sum of integers in an array.

www.hackerrank.com

 

소요시간 : 4분

 

풀이

function simpleArraySum(ar) {
    let result = ar.reduce((acc, cur) => { return acc + cur });
    return result;
}

1. reduce() 함수를 이용하여 누산함

2. 누산 값을 result 변수에 담아 리턴함

 

 

다른 사람의 풀이

function simpleArraySum(ar) {
	return ar.reduce((a, b) => a + b)
}

아..! 이렇게 한줄로 리턴했어도 됐는데...😅

'1Day 1Algorithm' 카테고리의 다른 글

[DAY 6] Recursion: Fibonacci Numbers  (0) 2019.10.06
[DAY 5] Flipping bits  (0) 2019.10.05
[DAY 4] Bitwise Operators  (0) 2019.10.04
[DAY 3] Compare the Triplets  (0) 2019.10.03
[DAY 1] Sock Merchant  (0) 2019.10.01
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함