假如学过数电大概是数理逻辑的话,这题应该不难,假如是数电的标题,实际上就是让你用与门和非门来实现异或。对于数理逻辑而言,也就是用与和非来实现异或,我们知道,异或就是差异则为1,类似则为0,对于单独的一位而言,就是1和0大概0和1这两种组合可以异或得到1,而对于位向量而言,也就是x&~y大概~x&y。这里须要一个或操纵,但是并不允许我们使用,那么思绪就是用与和非来实现或,在离散数学中我们知道,与和非这两个联结词的聚集是极小全功能的,等价于与或非这三个联结词的聚集,这是由于或是可以用与和非表现的,也就是x|y = ~(~x&~y),这里的证实可以使用 De Morgan’s laws 。于是只须要把这里的x和y更换成上面的两个就行了。
代码如下:
int bitXor(int x, int y) {
/*
Since "x bitXor y" equals "(x & ~y) | (~x & y)",
we just need to implement "|" with just "&" and "~".
And "x | y" equals "~(~x & ~y)".
*/
int x_and_noty = x & ~y;
int notx_and_y = ~x & y;
int not_x_and_noty = ~x_and_noty;
int not_notx_and_y = ~notx_and_y;
int x_bitXor_y = ~(not_x_and_noty & not_notx_and_y);
return x_bitXor_y;
}
复制代码
第2题 返回补码中的最小值Tmin
要求如下:
tmin - return minimum two's complement integer
Legal ops: ! ~ & ^ | + << >>
Max ops: 4
Rating: 1
复制代码
这题并不难,由于 T m i n Tmin Tmin 实际上就是100..0,一个1背面跟着31个0(由于int是32位的)。于是只须要将00..1,也就是十进制数值的+1,左移31位,就可以得到了。
代码如下:
[code]int tmin(void) { /* The bit expression of Tmin is 100..00, with one '1' followed by thirty-one '0'. So we just need to shift 000..01 left 31 positions, so that the '1' will be at the leftmost position, namely, Tmin. */ int one = 1; return one