Tuesday, November 22, 2011

easy one: swap 2 variables with no tmp

i know 2-3 ways. how many do you?

1 comment:

  1. 1) XOR:

    a = a xor b
    b = a xor b
    a = a xor b

    this is based on the same trick used to draw a line on a picture and remove it without store the overwritten pixels.

    2) Somme e sottrazioni:
    a = a + b;
    b = a - b;
    a = a - b;

    3) Una linea:
    b=(a+b)-(a=b);

    4) Ricorsivo:

    void swap( int& a, int& b) {
    if( a < b ) {
    --b;
    swap(a, b);
    ++a;
    } else if( a > b ) {
    --a;
    swap( a,b );
    ++b;
    }
    }

    bo non me ne vengono altri

    Ovviamente non si considerano self swap o problemi di overflow

    ReplyDelete