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的个数减去偶数个。以此类推,最后异或后得到一位,如

这篇博客介绍了如何利用计算机位运算规则来实现一个函数,该函数通过最多12次操作判断一个32位无符号整数x中1的个数是否为奇数。主要原理基于位异或操作,通过高16位与低16位的异或结果,递归地减少计算次数,最终确定x中1的数量是奇数还是偶数。
最低0.47元/天 解锁文章
3804

被折叠的 条评论
为什么被折叠?



