At Least One bit in int num is 0

时间:2016-02-03 03:19:06

标签: c

Trying to create a method that returns a 1 if the input int num has a zero in it using C without using if-else statements and using the bottom bitwise and boolean operators.

i tried this so far:

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.

2 个答案:

答案 0 :(得分:3)

Try this:

int hasAZero(int num) {
    return ~num != 0;
}

If num contains a zero bit, then its bitwise complement will contain a 1 bit and will be non-zero. If it does not contain a zero bit, then its complement will be zero.

If you don't want to use != then you can use !!~num instead as rpattiso pointed out (I wasn't clear is comparisons were allowed), i.e.:

int hasAZero(int num) {
    return !!~num;
}

答案 1 :(得分:1)

If I am understanding your question correctly, you want to check if there is a zero in a whole integer or 'string' of numbers? E.g. 13590 <-- 0 at the end.

To do this, you need to check each digit using a loop and see if that digit is equal to zero. Here's one way of doing it.

int hasAZero(int num) {
    int val = num;

    while (val >= 10) {
        if ((val % 10) == 0) {
            return 1;
        }
        val = val / 10;
    }

    return 0;
}