码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Xoring Ninja

时间:2015-04-23 07:10:00      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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!

HackerRank - Xoring Ninja

标签:

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!