1244번: 스위치 켜고 끄기 (acmicpc.net)
1244번: 스위치 켜고 끄기
첫째 줄에는 스위치 개수가 주어진다. 스위치 개수는 100 이하인 양의 정수이다. 둘째 줄에는 각 스위치의 상태가 주어진다. 켜져 있으면 1, 꺼져있으면 0이라고 표시하고 사이에 빈칸이 하나씩
www.acmicpc.net
핵심 구현
조건에 해당될 때마다 0이면 1로, 1이면 0으로 바꾸기
구현 방법
1. if - else문
if (num == 1) {
num = 0;
} else {
num = 1;
}
2. 뺄셈 활용
num = 1 - num;
num | 1 - num |
1 | 0 |
0 | 1 |
num이 1일 경우 1 - num = 0이다.
num이 0일 경우 1 - num = 1이다.
3. boolean 타입으로 저장
1과 0만 활용하므로 0일때는 false, 1일때는 true로 저장한다.
// int 입력을 boolean 타입으로 저장
boolean bool = (sc.nextInt() == 1);
// 부정연산자 활용해 변경
bool = !bool;
// 출력
System.out.print(Boolean.compare(bool, true) + 1);
Boolean.compare() 메소드는 아래와 같이 구현되어 있다.
public static int compare(boolean x, boolean y) {
return (x == y) ? 0 : (x ? 1 : -1);
}
bool == true일 경우 x == y 이므로 0을 리턴한다.
bool == false일 경우 (x ? 1 : - 1) 에서 -1을 리턴한다.
따라서 리턴값에 1을 더해주어야 원하는 형태로 출력이 된다.
4. xor 연산
num ^= 1;
num^1 연산의 진리표는 다음과 같다.
num | 1 | 결과값 |
0 | 1 | 1 |
1 | 1 | 0 |
xor 연산은 피연산자가 서로 다를 때만 1이 나오므로, num이 0이면 0^1 = 1이 된다. 반대로 num이 1이면 1^1 = 0이 된다.
전체 코드
import java.util.Scanner;
public class Main{
static boolean[] switches;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 초기 스위치 상태
int num = sc.nextInt();
switches = new boolean[num+1];
for (int i = 1; i < switches.length; i++) {
switches[i] = (sc.nextInt() == 1);
}
// 스위치 상태 변경
int cases = sc.nextInt();
for (int c = 0; c < cases; c++) {
boolean isMale = (sc.nextInt() == 1);
int input = sc.nextInt();
if (isMale) {
maleSwitch(input);
} else {
femaleSwitch(input);
}
}
// 최종 상태 출력
for (int i = 1; i < switches.length; i++) {
System.out.print((Boolean.compare(switches[i], true) + 1) + " ");
if (i % 20 == 0) {
System.out.println();
}
Integer.compare(cases, i)
}
}
// 남자 스위치 변경
public static void maleSwitch(int input) {
for (int i = input; i < switches.length; i += input) {
switches[i] = !switches[i];
}
}
// 여자 스위치 변경
public static void femaleSwitch(int input) {
switches[input] = !switches[input];
// 1~input과 input~마지막원소까지의 거리 중 최소값
int min = Math.min(input, switches.length-input) - 1;
for (int i = 1; i <= min; i++) {
if (switches[input-i] == switches[input+i]) {
switches[input-i] = !switches[input-i];
switches[input+i] = !switches[input+i];
} else {
return;
}
}
}
}
'Algorithm' 카테고리의 다른 글
[Java] 백준 23309번 - 철도 공사 (3) | 2025.07.22 |
---|---|
[Java] 백준 13172번 - Σ(시그마) (2) | 2024.05.02 |
[Java] 백준 11723번 - 집합 (0) | 2024.02.14 |
[Java] 백준 1149번 - RGB거리 (1) | 2024.02.10 |
[Java] SWEA - 두 개의 숫자열 (2) | 2024.01.11 |