[SWEA] 1986

ninano05·2026년 4월 3일

홀짝 나눠서 합하기

  • 홀수와 짝수를 구분하여 값을 합하거나 뺀다.
  • 홀수: n%2 == 1
  • 짝수: n%2 == 0
import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();

        int T = Integer.parseInt(br.readLine());

        for(int t=1; t<=T; t++) {
            int N = Integer.parseInt(br.readLine());
            int sum = 0;
            for(int i=1; i<=N; i++) {
                if(i%2 == 1){ //홀수인 경우
                    sum += i;
                } else if(i%2 == 0){ // 짝수인 경우
                    sum -= i;
                }
            }
            sb.append("#").append(t).append(" ").append(sum).append("\n");
        }
        System.out.println(sb);
        br.close();
    }
}
profile
초보 개발자

0개의 댓글