길이에 따른 연산

정경미·2023년 9월 23일

문제 설명
정수가 담긴 리스트 num_list가 주어질 때, 리스트의 길이가 11 이상이면 리스트에 있는 모든 원소의 합을 10 이하이면 모든 원소의 곱을 return하도록 solution 함수를 완성해주세요.

제한사항
2 ≤ num_list의 길이 ≤ 20
1 ≤ num_list의 원소 ≤ 9

입출력 예
num_list result
[3, 4, 5, 2, 5, 4, 6, 7, 3, 7, 2, 2, 1] 51
[2, 3, 4, 5] 120

입출력 예 설명
입출력 예 #1
리스트의 길이가 13이므로 모든 원소의 합인 51을 return합니다.

입출력 예 #2
리스트의 길이가 4이므로 모든 원소의 곱인 120을 return합니다.


Enumerable.Sum


using System;
using System.Linq;

public class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        int tmpValue = 1;
        if (num_list.Length >= 11){
             answer = num_list.Sum();
        } 
       else{
          for(int idx = 0; idx < num_list.Length; idx ++) 
          {tmpValue *= num_list[idx];
          }
           answer = tmpValue;
       }
        
        return answer;
    }
}

Enumerable.Aggregate

public static TResult Aggregate<TSource,TAccumulate,TResult> (this System.Collections.Generic.IEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate,TSource,TAccumulate> func, Func<TAccumulate,TResult> resultSelector);

시퀀스에 누적기 함수를 적용합니다. 지정된 시드 값은 초기 누적기 값으로 사용되고 지정된 함수는 결과 값을 선택하는 데 사용됩니다.

using System;
using System.Linq;
public class Solution {
    public int solution(int[] num_list) {
        int answer = num_list.Length <= 10 ? num_list.Aggregate((a, b) => a * b) : num_list.Sum();
        
        answer = num_list.Aggregate((total, next) =>
                                    num_list.Length >= 11 ? total + next : total * next);
        return answer;
    }
}

0개의 댓글