【发布时间】:2016-05-12 02:38:03
【问题描述】:
尝试创建一个方法,如果输入 int num 中包含零,则使用 C 语言创建一个返回 1 的方法,而不使用 if-else 语句并使用底部的位和布尔运算符。
到目前为止我已经试过了:
int hasAZero(int num){
return !(num && 1);
}
Bitwise AND (c = a & b) – c has 1s in the places where both of the corresponding bits in a and b are 1.
Bitwise OR (c = a | b) – c has 1s wherever at least one of the corresponding bits in a and b is 1.
Bitwise XOR (c = a ^ b) – c has 1s wherever one and only one of the corresponding bits in a and b is 1.
Bitwise NOT (c = ~a) – c is a, with each bit inverted, else c is 0.
Right shift (c = a >> b) – c is a, with each bit moved lower b places.
Left shift (c = a << b) – c is a, with each bit moved higher b places.
Boolean AND (c = a && b) – c is 1 if both a and b are non-zero.
Boolean OR (c = a || b) – c is 1 if either a and b are non-zero.
Boolean NOT (c = !a) – c is 1 only if a is 0.
【问题讨论】:
-
好吧,
num && 1总是非零,所以逻辑逆总是为零。不是很有用。为什么不直接使用~num != 0。如果您不想使用!=,那么您可以使用!!~num。 -
!!~num 只使用那些操作
-
澄清一下,您正在寻找一个 0 bit,对吗?不是像基诺的答案那样的十进制数字吗?
-
您能否详细说明“其中包含零”的含义?给出一些满足这个性质的例子,还有一些不满足的例子。你写了
&& 1(意思是“……和真”),这不是按位运算。想想你要测试什么,以及你将如何在现实生活中测试它。
标签: c