Comparing two integers without any comparison

前端 未结 14 1648
温柔的废话
温柔的废话 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:29
    char c;
    c=0x3D + (!(b/a) && (a-b)) - (!(a/b) && (a-b));
    printf("a %c b",c);
    
    0 讨论(0)
  • 2020-12-05 16:29
    (!(a/b) ?  cout << " b is greater than a" : (!(b-a) ? cout << "a and b are equal" :  cout << "a is greater than b") :  cout << "a is greater than b");
    

    That gets a bit messy though

    Edit: Is this homework?

    0 讨论(0)
  • 2020-12-05 16:30

    Try this, tested it, works well.

    public static int compare(int a, int b)
    {
        int c = a - b;
        return (c >> 31) & 1 ^ 1;
    }
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-05 16:33

    Subtract them and check the sign using nasty bit twiddling hacks
    http://graphics.stanford.edu/~seander/bithacks.html

    Don't do this in production code if the other programmers know where you live.

    0 讨论(0)
  • 2020-12-05 16:35

    I think this method is better than others, you can use this logic c and java both programming languages but int should be of 4 byte if int is of 2 byte then make 15 byte right shift instead of 31 byte.

    enter code here
    
    #include<stdio.h>
    
    main()
    {
       int a, b;
       printf("Enter three numbers\n");
       scanf("%d %d", &a, &b);
       printf("Largest number is %d \n",findMax( a,b ));
    }
    int findMax( int x, int y)
    {
      int z = x - y;
      int i  = (z  >>  31)  &  0x1;
      printf("i = %d shift = %d \n", i, (z>>31));
      int  max  =  x - i  *  z;
      return max;
    }
    
    0 讨论(0)
提交回复
热议问题