Comparing two integers without any comparison

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

    Here's a fun bit-twiddling version that doesn't have any conditional branches.

    int g = (int)"greater";
    int l = (int)"less";
    int e = (int)"equal";
    
    int a = 7;
    int b = 10;
    
    char *result = (char*)((((a - b) >> 31) & l) | (((b - a) >> 31) & g) | ((~((a - b) | (b - a))) >> 31) & e);
    cout << result;
    

提交回复
热议问题