알고리즘 문제를 해결하던 도중 비트 연산자(Bitwise Operators) 중에서 XOR 연산(배타적 논리합)에 대해 알아보게되었다.
XOR(Exclusive OR, 배타적 논리합) 연산은 두 비트가 다르면 1, 같으면 0을 반환하는 논리 연산이다.
int a = 5; // 5 = 101 (이진수)
int b = 3; // 3 = 011 (이진수)
int result = a ^ b; // XOR 연산 수행
System.out.println(result); // 출력: 6
^=
연산^=
연산자는 XOR 연산 후 결과를 다시 변수에 할당하는 연산자로 a ^= b
는 a = a ^ b
와 동일한 의미이다.
int a = 5; // 5 = 101 (2진수)
int b = 3; // 3 = 011 (2진수)
a ^= b; // a = a ^ b
System.out.println(a); // 출력: 6
^=
연산자 활용^=
연산자를 이용하면 추가 변수 없이 두 개의 변수 값을 교환할 수 있다.
int x = 7;
int y = 4;
x ^= y;
y ^= x;
x ^= y;
System.out.println("x: " + x + ", y: " + y); // 출력: x: 4, y: 7
연산 과정:
1. x = 7 (0111), y = 4 (0100)
2. x ^= y -> x = 3 (0011)
3. y ^= x -> y = 7 (0111)
4. x ^= y -> x = 4 (0100)
import java.util.Arrays;
import java.util.Comparator;
public class Test_78_TableHashFunction {
public int solution(int[][] data, int col, int row_begin, int row_end) {
// 정렬
Arrays.sort(data, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[col - 1] == b[col - 1]) {
return Integer.compare(b[0], a[0]); // 기본키(첫 번째 컬럼) 기준 내림차순
}
return Integer.compare(a[col - 1], b[col - 1]); // col 번째 기준 오름차순
}
});
// S_i 계산, XOR 연산
int answer = 0;
for (int i = row_begin - 1; i < row_end; i++) {
int sum = 0;
for (int value : data[i]) {
sum += value % (i + 1);
}
answer ^= sum; // XOR 연산
}
return answer;
}
}