HackerRank

This is a super interesting bit problem. This link can be found in discussion panel: http://math.stackexchange.com/questions/712487/finding-xor-of-all-subsets

So basic idea is to consider each bit at a time. 

- Assign each int with one bit, to indicate if it is selected or not, then there will be 2^N subsets (picture it in your mind)
- Since it is a all subsets, if bit[i] is on in ANY of the input, there will be two categories of subsets: one with bit[i] set, and the other without. So, the no. of subsets contribute to final bit[i] will be 2^(N-1). And since it is bit[i], we need left shift it by i bits to contribute to final value of sum: 2^(N-1+i)
- Please note "ANY" above, it leads to OR operation
- Each bit contribute as 2^(N-1+i) * or_all[i], get the common factor 2^(N-1) out, and you will get the correct answer.

And since we will be using very large integer type, Python is a much better choice than C++:

# Enter your code here. Read input from STDIN. Print output to STDOUT
t = int(input())
for _ in range(t):
    n = int(input())
    arr = map(int, raw_input().split())
    xor_sum = 0
    for i in range(n):
        xor_sum |= arr[i]
    pwr = 1 << (n - 1)
    print (pwr * xor_sum % 1000000007)

A super neat code piece that solves a non-trivial problem!

原文地址:https://www.cnblogs.com/tonix/p/4449245.html