2.65 Odd Ones

★★★★

Problem:

Write code to implement the following function:

/* Return 1 when x contains an odd number of 1s; 0 otherwise. Assume w=32 */
int odd_ones(unsigned x);

Your function should contain a total of at most 12 arithmetic, bitwise, and logical operations.

code:

#include <stdio.h>
#include <assert.h>

int odd_ones(unsigned x) {
    x ^= x >> 16;
    x ^= x >> 8;
    x ^= x >> 4;
    x ^= x >> 2;
    x ^= x >> 1;
    return x & 0x1;
}

int main() {
    unsigned uval = 0x10101010;
    assert(!odd_ones(uval));
    uval = 0x10101011;
    assert(odd_ones(uval));
    return 0;
}

Last updated