Comparing two integers without any comparison

前端 未结 14 1646
温柔的废话
温柔的废话 2020-12-05 16:06

Is it possible to find the greatest of two integers without any comparison? I found some solutions:

if(!(a/b)) // if a is less than b then division result          


        
14条回答
  •  有刺的猬
    2020-12-05 16:48

    You can use a function to check equal or not using xor bitwise operator. here, you can write this function as:

    int Check(int a, int b){
        return (a^b);
    }
    

    This function will return 0, if two integers are same, otherwise not.

    Here, included an example to understand this function.

    Let take two integers as a = 1, b= 2

    the bits of 1 is --> 00000001 and for 2 is --> 00000010

    if we apply xor operation here, we'll get the result as 00000000 which is 0 in integer. because the xor operations are:

    1 xor 1 = 0
    1 xor 0 = 1
    0 xor 1 = 1
    0 xor 0 = 0
    

    Another way you can do by subtracting the number like

    int Check(int a, int b)
    {
       return abs(a-b);
    }
    

    The logic here will work as same as before. If we get 0 then it should be equal otherwise not!

提交回复
热议问题