Comparing two integers without any comparison

前端 未结 14 1647
温柔的废话
温柔的废话 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:31

    To get the greatest number without using comparison/relational operator

    void PrintGreatestNumber(int a, int b)
    {
       int [] x = new int[] { -1, 0, 1 };
       int greatestNumber =  ((a+b)+ x[ 1 + ((a-b) >> 31) - (-(a-b) >> 31)] * (a-b)) /2;  
       Console.WriteLine(greatestNumber);
    }
    

提交回复
热议问题