1986. 지그재그 숫자
by youngjun._.
삼성 SWExpertAcademy 알고리즘 문제
1986. 지그재그 숫자
1부터 N까지의 숫자에서 홀수는 더하고 짝수는 뺐을 때 최종 누적된 값을 구해보자.
[예제]
N이 5일 경우,
1 – 2 + 3 – 4 + 5 = 3
N이 6일 경우,
1 – 2 + 3 – 4 + 5 – 6 = -3
[제약사항]
N은 1 이상 10 이하의 정수이다. (1 ≤ N ≤ 10)
[입력]
가장 첫 줄에는 테스트 케이스의 개수 T가 주어지고, 그 아래로 각 테스트 케이스가 주어진다.
각 테스트 케이스에는 N이 주어진다.
[출력]
각 줄은 ‘#t’로 시작하고, 공백을 한 칸 둔 다음 누적된 값을 출력한다.
(t는 테스트 케이스의 번호를 의미하며 1부터 시작한다.)
> 입력
2
5
6
> 출력
#1 3
#2 -3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
/* 20.08.13 | |
* SW Expert Academy | |
* [1986] 지그재그 숫자 | |
* 1부터 N까지의 숫자에서 홀수는 더하고 짝수는 뺐을 때 최종 누적된 값 | |
*/ | |
public class N1986 { | |
public static void main(String[] args) { | |
Scanner scan = new Scanner(System.in); | |
int test = scan.nextInt(); | |
for (int test_case = 1; test_case <= test; test_case++) { // test case 만큼 Loop | |
int number = scan.nextInt(); | |
int sol = 0; | |
for(int i = 1; i <= number; i++) { | |
if(i%2 == 0) { // 짝수 일 경우 빼기 | |
sol -= i; | |
} | |
else { | |
sol += i; | |
} | |
} | |
System.out.println("#" + test_case + " " + sol); | |
} | |
scan.close(); | |
} | |
} |
블로그의 정보
개발하는만두
youngjun._.