Help with "Sum of All Subset XOR Totals" Problem

Revision en2, by copycat69, 2025-04-01 12:42:11

I was solving Sum of All Subset XOR Totals on Leetcode. It was obviously a Backtracking problem so I solved it in n*(2^n) . But it surprisingly has a linear solution. Like this

class Solution {
public:
    int subsetXORSum(vector<int>& nums) {
        int sum=0;
        for(auto i:nums)sum|=i;
        return sum*(1<<(nums.size()-1));
    }
};

Why this works ? Does anyone have the proof??

Tags bit, bitmask, leetcode

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en2 English copycat69 2025-04-01 12:42:11 12 Tiny change: 'ved it in both n*(2^n) and 2^n. But it s' -> 'ved it in n*(2^n) . But it s'
en1 English copycat69 2025-04-01 12:16:13 544 Initial revision (published)