x^0 = x
Xor of any number with 0 is the number itself.
x^x = 1
XOR of any number with itself is 0 because each bit cancels itself out. For example, 5 ^ 5 = 0.
This problem utilises above mentioned properties
This problem utilises above mentioned properties but is slightly more complicated than the first problem
Hamming distance between two integers (or binary strings) is the number of bit positions at which the corresponding bits are different. Example: x = 5 → 0101 y = 3 → 0011 Hamming distance = 2 (1, 2 index);
int hammingDistance(int x, int y) {
return __builtin_popcount(x ^ y); // XOR + count set bits
}
This problem utlizes hamming distance concepts.
Each subset of a given array can be represented by a binary number, where each bit indicates whether to include a particular element.
By looping from 0
to 2n - 1
, we generate all possible combinations.
For each number i
, the expression (i >> j) & 1
checks if the j
-th bit is set.
If it is, we include nums[j]
in the current subset.
For example, if nums = [1, 2, 3]
and i = 5
(binary 101
), we include nums[0]
and nums[2]
,
resulting in the subset [1, 3]
. This method efficiently generates all subsets using bitmasking. Sample code:
for (int i = 0; i < (1 << nums.size()); ++i) {
vector<int> subset;
for (int j = 0; j < nums.size(); ++j) {
if ((i >> j) & 1) {
subset.push_back(nums[j]);
}
}
ans.push_back(subset);
}