The bit value is less than or equal to

There seems to be some misconception that this is for the contest. I’m trying to complete a task, and for an hour now I’ve been stuck on it.

 /*
     * isLessOrEqual - if x <= y  then return 1, else return 0 
     *   Example: isLessOrEqual(4,5) = 1.
     *   Legal ops: ! ~ & ^ | + << >>
     *   Max ops: 24
     *   Rating: 3
     */
    int isLessOrEqual(int x, int y)
    {
        int greater = (x + (~y + 1))>>31 & 1;
        return !(greater)|(!(x^y));

    }

I can use bitwise operators as indicated in the comments. I cannot figure out how to solve x <= y;

My thought process is that I can set x as its two additions (~ x +1) and add it with Y. If it is negative, X is greater than Y. Therefore, denying that I can get the opposite effect,

Similarly, I know that! (x ^ y) is equivalent to x == y. However, do! (more) | (! (x ^ y)) does not return the correct value.

Where will I mix up? I feel that I have little logic.

+2
source share
2 answers

x > y, y - x (y + (~x + 1)) , 1, 0. x <= y, .

    /*
     * isLessOrEqual - if x <= y  then return 1, else return 0 
     *   Example: isLessOrEqual(4,5) = 1.
     *   Legal ops: ! ~ & ^ | + << >>
     *   Max ops: 24
     *   Rating: 3
     */
    int isLessOrEqual(int x, int y)
    {
        return !(((y + (~x + 1)) >> 31) & 1);
    }

:

    int isLessOrEqual(int x, int y)
    {
        return !((y + (~x + 1)) & 0x80000000);
    }

EDIT:

. , .

#include <limits>
int isLessOrEqual(int x, int y)
{
    static int const vm = std::numeric_limits<int>::max();
    static int const sm = ~vm;

    return  !! ((x & ~y | ~(x ^ y) & ~((y & vm) + ~(x & vm) + 1)) & sm);
}

: , , " " , , . , , . .

int , , std::numeric_limits<int>::max() . - - .

<=, - sm . x & ~y true, x y . ~(x ^ Y) , . ~((y & vm) + ~(x & vm) + 1)) , y - x , x <= y, . or'd, ++ :

x < 0 && y >= 0 || (x < 0 && y < 0 || x >= 0 && y >= 0) && y - x >= 0

!! 1. , constexpr Modern ++:

template<typename T>
constexpr T isLessOrEqual(T x, T y)
{
    using namespace std;
    // compile time check that type T makes sense for this function
    static_assert(is_integral<T>::value && is_signed<T>::value, "isLessOrEqual requires signed integral params");

    T vm = numeric_limits<T>::max();
    T sm = ~vm;

    return  !! ((x & ~y | ~(x ^ y) & ~((y & vm) + ~(x & vm) + 1)) & sm);
}
+1

- , . ...

int isLessOrEqual(int x, int y) {
int diff_sgn = !(x>>31)^!(y>>31);      //is 1 when signs are different
int a = diff_sgn & (x>>31);            //diff signs and x is neg, gives 1
int b = !diff_sgn & !((y+(~x+1))>>31); //same signs and difference is pos or = 0, gives 1
int f = a | b;
return f;
}
+3

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


All Articles