Home | Projects | Notes > Problem Solving > EPI - 5.1. Computing the Parity of a Word (bit manipulation)
This solution uses brute-force approach that iteratively tests the value of each bit while tracking the number of 1s seen so far.
Complexity Analysis:
Solution:
x1short Parity(unsigned long x)
2{
3 short result = 0;
4
5 while (x)
6 {
7 result += (x & 1);
8 x >>= 1;
9 }
10
11 return result % 2;
12}
This can be re-written as follows:
xxxxxxxxxx
121short Parity(unsigned long x)
2{
3 short result = 0;
4
5 while (x)
6 {
7 result ^= (x & 1);
8 x >>= 1;
9 }
10
11 return result;
12}
This solution improves the Solution 1 by using the technique "Erase the lowest set bit in a word in a single operation" (x = x & (x - 1)
.
Complexity Analysis:
Solution:
xxxxxxxxxx
121short Parity(unsigned long x)
2{
3 short result = 0;
4
5 while (x)
6 {
7 result ^= 1;
8 x = x & (x - 1); // Drop the lowest set bit of x
9 }
10
11 return result;
12}