尝试使用 C 创建一个方法,如果输入 int num 中有零,则返回 1,而不使用 if-else 语句并使用底部按位和 bool 运算符。
到目前为止我尝试过:
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.
最佳答案
试试这个:
int hasAZero(int num) {
return ~num != 0;
}
如果 num
包含零位,则其按位补码将包含 1
位且非零。如果它不包含零位,则其补码为零。
如果您不想使用 !=
那么您可以使用 !!~num
代替,正如 rpattiso 指出的那样(我不清楚是否允许比较),即:
int hasAZero(int num) {
return !!~num;
}
关于c - int num 中至少一位为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35167897/