상세 컨텐츠

본문 제목

홀수 vs 짝수

코딩테스트/C#

by MJ_119 2024. 6. 16. 02:17

본문

문제 설명

정수 리스트 num_list가 주어집니다. 가장 첫 번째 원소를 1번 원소라고 할 때, 홀수 번째 원소들의 합과 짝수 번째 원소들의 합 중 큰 값을 return 하도록 solution 함수를 완성해주세요. 두 값이 같을 경우 그 값을 return합니다.


제한사항
  • 5 ≤ num_list의 길이 ≤ 50
  • -9 ≤ num_list의 원소 ≤ 9

입출력 예

 

 

using System;

public class Solution {
    public int solution(int[] num_list) {
        int answer = 0;
        int a = 0;
        int b = 0;
        
        for(int i = 0; i< num_list.Length; i += 2)
        {
            a += num_list[i];
        }
        
        for(int i = 1; i< num_list.Length; i += 2)
        {
            b += num_list[i];
        }
        
        answer = a > b ? a : b;
        
        return answer;
    }
}

 

다른 풀이

using System;

public class Solution {
    public int solution(int[] num_list) {

        int even = 0;
        for(int i = 0; i < num_list.Length; i += 2)
            even += num_list[i];

        int odd = 0;
        for(int i = 1; i < num_list.Length; i += 2)
            odd += num_list[i];

        return Math.Max(even, odd);
    }
}

'코딩테스트 > C#' 카테고리의 다른 글

n 번째 원소까지  (1) 2024.06.17
5명씩  (0) 2024.06.16
n 번째 원소부터  (0) 2024.06.16
l로 만들기  (0) 2024.06.13
배열에서 문자열 대소문자 변환하기  (0) 2024.06.13

관련글 더보기