문제

https://www.acmicpc.net/problem/2830


문제 풀이

  • XOR 연산을 하기때문에 모든 수에 대해 (각 자리의 1의 개수) X (각 자리의 0의 개수)를 XOR 했을 때 각 자리의 1의 개수가 나오고, 그것을 전부 합한 뒤에 자리수를 곱해주면 된다.

  • 예를들어 예제2번을 2진수로 표현하면 (111, 011, 101) 이다.

    각 자리수를 1의 갯수 x 0의 갯수로 표시한다(백의자리 : 2x1 , 십의자리 : 1x2, 일의자리 3x0)

    그러면 예제의 답은 2x22 + 2x21 + 0x1 로 12이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] arr = new int[20];

        for (int i = 0; i < n; i++) {
            int num = sc.nextInt();
            for (int j = 0; j < 20; j++) {
                if ((num & (1 << j)) > 0) arr[j]++;
            }
        }

        long answer = 0;
        for (int i = 0; i < 20; i++) {
            int zeroCount = n - arr[i];
            answer += (long)(1 << i) * zeroCount * arr[i];
        }
        System.out.println(answer);

    }
}

카테고리:

업데이트:

댓글남기기