In c binary, testing to see if a number is in the range

This is part of the puzzle that I cannot understand. The function accepts three inputs. The first is int, the second is the lower bound, and the third is the upper bound. I need to check if this first number is in the lower and upper bounds inclusive.

If it is in a range, return 1, otherwise return 0. The trick is that I can only use

! ~ & ^ | + << >> 

and only a combination of 20 of them. In addition, only int variables and if, loop, or function statements can be used.

Range(int x, int lower, int upper){
//... some code here
return retVal;
}

Obviously, I understand the logic here. If ((x> = lower) && (x <= upper)) returns 1; The only problem is that I cannot use the if, lt ;,>, == or & & operators.

+4
source share
4 answers

I like these puzzles! For this you need to have something like

Well, to be abstract on this, you need to have 2 variables.

The first variable (lets call it blarg) you need to set the upper border and add an inverted x. Now you need to add one to blarg and flip it.

The second variable (allows you to hold it) will add x to the inverted lower bound; After that, add 1 to hold and flip it too.

set blarg = to blarg plus hold; shift blarg over 31 to the right. and AND with 1.

It should be what you are looking for.

+1
source

x < y ( -1, true, 0, false), : (. Hacker Delight, 2, )

((x - y) ^ ((x ^ y) & ((x - y) ^ x))) >> 31;

, x - y ~(~x + y)

, 1 & ~((x < lower) | (upper < x))

, , 32- . , .


:

int in_range(int x, int lower, int upper)
{
    int p = ((x - lower) ^ ((x ^ lower) & ((x - lower) ^ x))) >> 31;
    int q = ((upper - x) ^ ((upper ^ x) & ((upper - x) ^ upper))) >> 31;
    return 1 & ~(p | q);
}

, , .

, >= <= ( Hacker Delight).

, .


, , , :

int p = (x | ~upper) & ((x ^ upper) | (~upper + x));
int q = (lower | ~x) & ((lower ^ x) | (~x + lower));
return 1 & ((p & q) >> 31);

<= HD, (x | ~y) & ((x ^ y) | ~(y - x)) .

, .

+7

do it. I will talk about the logic that you can use.

a=~x+1    //gives -x
b=lower+a   //lower-x
c=~upper+1    //gives -upper
d=x+c           //x-upper  
b=b&0x80000000;   //get the msb which is 1 if -ve number
d=d&0x80000000;
return ((b&d)|(!(x^lower))|(!(x^upper)));  //& results in +ve only if both b & d are +ve
+3
source

Here is a modest solution

int foo(int num, int upp, int low){
        return (~((~(upp + ~num + 1)) ^ (~(num + ~low + 1))) >> 31) & 1;
}
+3
source

Source: https://habr.com/ru/post/1529277/


All Articles