- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Sum of XOR of all possible subsets in C++

In this problem, we are given an array aar[] of n numbers. Our task is to create a program to find the Sum of XOR of all possible subsets.

Here, we will find all subsets of the array. Then for each subset, we will find the XOR of elements of the subset and add them to the sum variable.

## Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 4} Output: 20 Explanation: XOR of all subsets: {5} = 5 {1} = 1 {4} = 4 {5, 1} = 4 {5, 4} = 1 {1, 4} = 5 {5, 1, 4} = 0 Sum of XOR = 5 + 1 + 4 + 4 + 1 + 5 = 20

A simple solution to the problem, is using loop and find all possible subsets of the array and then for each subset find XOR of all the elements and update the sum. Return sum at the end.

This is not an effective approach, for the large value, the time complexity will grow exponentially.

An efficient approach is using the properties of XOR. Here, we will find the OR of all elements of the array and check the bits. If the ith is set, then update sum with (2^(n-1+i)).

## Example

Program to illustrate the working of our solution,

#include <iostream> #include <math.h> using namespace std; int subSetXORSum(int arr[], int n) { int bitOR = 0; for (int i=0; i < n; ++i) bitOR |= arr[i]; return (bitOR * pow(2, n-1)); } int main() { int arr[] = {1, 5, 4}; int size = sizeof(arr) / sizeof(arr[0]); cout<<"Sum of XOR of all possible subsets is "<<subSetXORSum(arr, size); }

## Output

Sum of XOR of all possible subsets is 20

- Related Questions & Answers
- Sum of the products of all possible Subsets in C++
- Finding all possible subsets of an array in JavaScript
- Sum of XOR of all subarrays in C++
- XOR of Sum of every possible pair of an array in C++
- Sum of XOR of sum of all pairs in an array in C++
- Sum of XOR of all pairs in an array in C++
- Sum of all subsets of a set formed by first n natural numbers
- Sum of All Possible Odd Length Subarrays in JavaScript
- Maximum possible difference of two subsets of an array in C++
- Count number of subsets having a particular XOR value in C++
- Program to find XOR sum of all pairs bitwise AND in Python
- Python program to get all subsets having sum s
- XOR of all subarray XORs in C++
- Print all subsets of given size of a set in C++
- Print all possible sums of consecutive numbers with sum N in C++