/* Return 1 when any odd bit of x equals 1; 0 otherwise. Assume w = 32 */
#include <stdio.h>
int any_odd_one(unsigned x)
{
unsigned mask = 0xAAAAAAAA;
return !!(x & mask);
}
int main(void)
{
int result = any_odd_one(2);
printf("result:%d
", result);
result = any_odd_one(3);
printf("result:%d
", result);
return 1;
}
/*
* Return 1 when x contains an odd number of 1s; 0 otherwise.
* Assume w=32.
* 函数应遵循位级正数编码规则,不过你可以假设数据类型 int有 w=32位。
* 你的代码最多只能包含12个算数运算、位运算和逻辑运算。
*/
int odd_ones(unsigned x)
{
x ^= x>>16;
x ^= x>>8;
x ^= x>>4;
x ^= x>>2;
x ^= x>>1;
x &= 1;
return !!x;
}
int main(void)
{
printf("result: %d
", odd_ones(3));
printf("result: %d
", odd_ones(2));
printf("result: %d
", odd_ones(0xAAAAAAAA));
printf("result: %d
", odd_ones(0xAAAAAAA8));
return 1;
}