포스트

홀짝에 따른 다른 값 반환하기

https://school.programmers.co.kr/learn/courses/30/lessons/181935

문제

  • 문제 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
    public int solution(int n) {
        int result = 0;

        if (n % 2 == 1) { // 홀수일 때
            for (int i = 1; i <= n; i += 2) {
                result += i;
            }
        } else { // 짝수일 때
            for (int i = 2; i <= n; i += 2) {
                result += i * i;
            }
        }

        return result;
    }
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.