[Swift] Array의 Sum 구하기
👨🏻‍💻iOS 공부/Swift_알고리즘 풀이

[Swift] Array의 Sum 구하기

728x90
반응형

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

For example, if the array , so return .

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

Input Format

The first line contains an integer, , denoting the size of the array.
The second line contains  space-separated integers representing the array's elements.

Constraints

Output Format

Print the sum of the array's elements as a single integer.

Sample Input

6
1 2 3 4 10 11

Sample Output

31

Explanation

We print the sum of the array's elements: .








swift에서 Array 요소들의 합을 구하고자 할 때는 reduce를 사용한다. 







reduce의 첫 번째 인자는 시작값이다. 즉 0으로 적어줄 경우, 0의 값을 가지고 연산을 하라는 것이다.

그리고 두 번째 인자는 어떠한 연산을 할지에 대해 적어준다. +를 적으면 값을 하나씩 더하게 되는 것이고, -,+,/ 모두 적용 가능하다. 


func simpleArraySum(ar: [Int]) -> Int {
    return ar.reduce(0,+)
}




728x90
반응형