diff options
author | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
---|---|---|
committer | jack <[email protected]> | 2024-06-14 13:13:15 -0600 |
commit | d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa (patch) | |
tree | 96df922dae2a5073d9a50ea70c7aae6aa37e3ebe /sum_subset_xor.cpp | |
download | leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.tar.gz leetcode-d343a3b18dbaca9297d4f7b2280c4a16f0a5c8aa.zip |
initial
Diffstat (limited to 'sum_subset_xor.cpp')
-rw-r--r-- | sum_subset_xor.cpp | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/sum_subset_xor.cpp b/sum_subset_xor.cpp new file mode 100644 index 0000000..a3048f7 --- /dev/null +++ b/sum_subset_xor.cpp @@ -0,0 +1,33 @@ +#include "leetcode.h" + +/* + 000 => {empty set} + 001 => {set with only first element} + 010 => {set with only second element} + 011 => {set with first and second element} + 100 ... and so on + 101 + 110 + 111 => {subset with all three elements} +*/ + +class Solution { +public: + int subsetXORSum(vector<int> &nums) { + int n = nums.size(), subsetNum = pow(2, n), ans = 0; + for (int i = 1; i < subsetNum; ++i) { + int runningXOR = 0; + for (int j = 0, bits = i; j < nums.size(); ++j, bits >>= 1) + if (bits & 1) + runningXOR ^= nums[j]; + ans += runningXOR; + } + return ans; + } +}; + +int main() { + vector<int> nums = {3, 4, 5, 6, 7, 8}; + Solution obj; + cout << obj.subsetXORSum(nums); +} |