짝수의 합

반즈·2023년 11월 10일

프로그래머스 입문

목록 보기
1/51

문제 설명

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

입출력 예

자바

나의 풀이

class Solution {
    public int solution(int n) {
        int answer = 0;
        int tempNum = 0;
        if(n % 2 == 0) {
            while(n != 0){
                tempNum += n;
                n = n - 2;
            }
        } else if(n % 2 != 0){
            n = n - 1;
            while(n != 0){
                tempNum += n;
                n = n - 2;
            } 
        }
        answer = tempNum;
        return answer;
    }
}

참고 풀이 1 (0부터 - for문)

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

        for(int i=2; i<=n; i+=2){
            answer+=i;
        }

        return answer;
    }
}

참고 풀이 2 (IntStream)

import java.util.stream.IntStream;
class Solution {
    public int solution(int n) {
        return IntStream.rangeClosed(0, n)
            .filter(e -> e % 2 == 0)
            .sum();
    }
}

자바스크립트

나의 풀이

function solution(n) {
    var answer = 0;
    while(n != 0){
        if(n % 2 == 0){
            answer += n;
            n -= 2;
        } else {
            n -= 1;
        }
    }
    return answer;
}

참고풀이 1 (0부터 - for문)

function solution(n) {
    var answer = 0;

    for(let i=2 ; i<=n ; i+=2)
        answer += i;

    return answer;
}
profile
나를 채우다

0개의 댓글