본문 바로가기
프로그래머/프로그래머스

C#)프로그래머스_짝수의 합

by FourthWay 2023. 2. 20.
728x90
반응형

문제설명

정수 n 이 주어질 때, n이하의 짝수를 모두 더한 값을 return 하도록 solution 함수를 작성해 주세요.

 

제한사항

  • 0 <n <=1000

입출력 예

n result
10 30
4 6

 

입출력 예 설명

입출력 예 #1

  • n이 10이므로 2+4+6+8+10=30을 return 합니다.

입출력 예 #2

  • n이 4이므로 2+4=6을 return 합니다.

나의 풀이

using System;

public class Solution
{
 public int solution(int n)
 {
  if(0<n && n<=1000);
  
  for(int i=2; i<=n; i++)
  {
   if(i % 2==0)
   answer += i;
  }
   return answer;
 }
}
테스트 1
입력값 10
기댓값 30
실행 결과 테스트를 통과하였습니다.
테스트 2
입력값 4
기댓값 6
실행 결과 테스트를 통과하였습니다.

 

다른 사람들의 풀이

using System;

public class Solution 
{
    public int solution(int n) 
    {
        int answer = 0;
        int count = n/2;
        for(int i = 1 ; i <= count; i++)
        {
            answer += 2*i;
        }
        return answer;
    }
}




using System;

public class Solution 
{
    public int solution(int n) 
    {
        int answer = 0;
        int min = 1;   

        for(int i = min; i <= n; i++)
        {
            if(i % 2 == 0)
            {
                answer += i;                
            }
            else    
            {continue;}
        }

        return answer;
    }
}





using System;

public class Solution 
{
    public int solution(int n) 
    {
        return n/2*(n/2+1);
    }
}






using System;

public class Solution 
{
    public int solution(int n) 
    {
        int answer = 0;
        if(n>0 && n <= 1000)
        {
            do{
                if(n%2 == 0) answer += n;
                n--;
            }while(n > 0);
        }
        else
        {
         string etc = "n의 값은 0~1000사이의 값을 입력해주세요.";
         Console.WriteLine(etc);
        }
        return answer;
    }
}





using System;

public class Solution 
{
    public int solution(int n) 
    {
        int answer = 0;

        for(int i = 0; i <= n; i++)
            answer += i % 2 == 0? i : 0;

        return answer;
    }
}

 

728x90
반응형