employer cover photo
employer logo

Question d’entretien chez Convergys

Swap two numbers without a temporary variable

Réponses aux questions d'entretien

Utilisateur anonyme

30 avr. 2010

x=x+y y=x-y x=x-y

Utilisateur anonyme

6 juil. 2011

The way i've remembered this and it's just slightly faster than the plus minus thing is the butterfly swap or as myself and friends have dubbed it affectionately as the 'butterflizzle swizzle' x ^= y; y ^= x; x ^= y; if you know what the XOR binary operation does you can physically step through this process yourself to see just how it works. the only problem here is that if you try to swap two variables that are the same you'll find it will zero out both variables. Just do a simple if( x != y ) before you start swizzling and everything will be cool