상세 컨텐츠

본문 제목

등차수열의 특정한 항만 더하기

코딩테스트/C#

by MJ_119 2024. 6. 10. 18:34

본문

문제 설명

두 정수 a, d와 길이가 n인 boolean 배열 included가 주어집니다. 첫째항이 a, 공차가 d인 등차수열에서 included[i]가 i + 1항을 의미할 때, 이 등차수열의 1항부터 n항까지 included가 true인 항들만 더한 값을 return 하는 solution 함수를 작성해 주세요.


제한사항
  • 1 ≤ a ≤ 100
  • 1 ≤ d ≤ 100
  • 1 ≤ included의 길이 ≤ 100
  • included에는 true가 적어도 하나 존재합니다.

 

using System;

public class Solution {
    public int solution(int a, int d, bool[] included) {
        int answer = 0;
        
        int total = a;
        
        for(int i = 0; i < included.Length; i++)
        {
            if(included[i])
            {
                answer += total;
            }
            total += d;
        }
        
        return answer;
    }
}

 

 

다른 답변

using System;

public class Solution {
    public int solution(int a, int d, bool[] included) {
        int answer = 0;
        for(int i=0;i<included.Length;i++)
        {
            if(included[i] == true) 
            	answer += a + d * i;
        }
        return answer;
    }
}

 

 

 

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

원소들의 곱과 합  (0) 2024.06.10
주사위 게임 2  (0) 2024.06.10
코드 처리하기  (1) 2024.06.10
flag에 따라 다른 값 반환하기  (0) 2024.06.10
홀짝에 따라 다른 값 반환하기  (0) 2024.06.10

관련글 더보기