c - int num 中至少一位为 0

标签 c

尝试使用 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/

相关文章:

c - 为什么使用返回值时0会被移入堆栈?

c - OpenGL Ubuntu 深度

c - 函数指针参数被忽略/不需要

c++ - 标准内容的库(即 : cout, 等)*新手问题* :)

c - 在 Solaris 中列出共享库的依赖项

c - 不同小数点定点优化算法

c - 使用但未定义的标签

c - 在运行时声明和初始化 C 中的类数组

java - 整数的最大值

c# - 将 Visual Studio 6 库转换为 Visual Studio 10