Write code to implement the following functions:
/*Return 1 when x contains an odd number of 1s; 0 otherwise.
Assume w = 32. */
int odd_ones(unsigned x);
Your function should follow the bit-level integer coding rules(page 120),except that you may assume that data type int has w = 32 bits.
Your code should contain a total of at most 12 arithmetic, bit-wise, and logical operations.
解答:
用到的主要原理:1. 1^1 = 1 0^0 = 0 1^0 = 1 0^1=1
2. 奇數 - 偶數 = 奇數,偶數 - 偶數 = 偶數
,對於unsigned x,高16位與低16位異或,因為1^1 = 0,得到的16bit中含1的個數恰好是x中1的個數減去偶數個。以此類推,最後異或後得到一位,如果是1,就說明x含奇數個1,若是0,則說明x含偶數個1。
編寫代碼是為了減少操作,用x的一部分儲存b。
int odd_ones(unsigned x){ //用x的低16位表示b,x ^ a 對應 b ^ a unsigned a = x >> 16; x = x ^ a; //用x的低8位表示b a = x >> 8; x = x ^ a; //用x的低4位表示b a = x >> 4; x = x ^ a; //用x的低2位表示b a = x >> 2; x = x ^ a; //用x的低1位表示b a = x >> 1; x = x ^ a; //此時,x的最低1位即最後的結果 return x & 0x1;}