Comparing two integers without any comparison

前端 未结 14 1650
温柔的废话
温柔的废话 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 might exploit the fact that the sign of the calculation a - b depends on which number is greater. This is used in many implementations of comparison. But I believe you'll never be able to completely avoid comparison. In this case, you still at least need to evaluate the contents of the sign flag on the processor.

    If you just need to display the lower number you can also use arithmetic tricks:

    result = ((a + b) - sqrt((a - b) * (a - b))) / 2
    

    EDIT erm … you're allowed to use switch?

    I should use switch statements and arithmetic operators.

    switch is basically the same as chained if and as such it also uses comparison. This sounds as if you should indeed just compare to zero to see what sign a - b has.

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题