Comparing two integers without any comparison

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

    I just cant see any good reason to do that : who would want to program without "if" ?

    a possible answer is :

    ( ( a + b ) + abs ( a -b ) ) / 2

    I guess "abs" just hides a "if" somewhere, just as the ternary operator that is just another name for "if" ...

    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-05 16:40

    As a pointless exercise, here's a way of implementing a cond function - to serve the purpose of if, supposing it (and switch, and ?:) had somehow disappeared from the language, and you're using C++0x.

    void cond(bool expr, std::function<void ()> ifTrue, std::function<void ()> ifFalse)
    {
        std::function<void ()> choices[2] = { ifTrue, ifFalse };
        choices[expr == false]();
    }
    

    e.g.

    cond(x > y,
        /*then*/ [] { std::cout << "x is greater than y"; },
        /*else*/ [] { std::cout << "x is not greater than y"; });
    

    Like I say, pointless.

    0 讨论(0)
  • 2020-12-05 16:40
    void greater(int a, int b) {
        int c = a - b;
        switch(c) {
            case 0:
                cout << "a and b are equal" << endl;
                break;
            default:
                int d = c & (1<<31);
                switch(d) {
                    case 0:
                        cout << "a is bigger than b" << endl;
                        break;
                    default:
                        cout << "a is less than b" << endl;
                }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 16:46

    Not one of the samples presented in the question or any of the answers thus far protects from division by zero. Why on earth are you trying to avoid an 'if' statement? I suspect homework question about ?: operators.

    cout << "Maximum is: " << ((a>b)?a:b)
    

    There we go.

    It's not possible to compare two numbers without a comparison. You can fudge it and do an indirect operation, but at the end of the day you're comparing something. Trust the compiler to optimize the code and select the best operations.

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

    The Perverse Idea: use an array of function pointers. Then with some arithmetic and bitwise operations get an index into that array.

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