Swap the value of two integers without temporary storage

Someone says this is an old lame trick. I think it鈥檚 simple and clever use of XOR. How/Why does it work? It鈥檚 built around the properties of the XOR ^ operator, who has the following properties: A ^ B = B ^ A (commutative) A ^ 0 = A A ^ 1 = ~A A ^ A = 0 So, you can see how it get鈥檚 applied here: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #include <stdio .h> int main(void) { unsigned int a, b; // ... populate somehow "a" and "b"... printf("a = %d - b = %d\n", a, b); a ^= b; // store in "a" the value of "a XOR b" b ^= a; // store in "b" the value of "a XOR b XOR b" = "a XOR 0" = "a" a ^= b; // store in "a" the velue of "a XOR b XOR a" = "b XOR 0" = "b" printf("a = %d - b = %d\n", a, b); } Neat.

January 13, 2010 路 1 min 路 174 words

Largest square array of same integers

Tonight it鈥檚 a challenging one. Or, better, a problem of which is really difficult to find a good solution in < O(n3). Indeed, it鈥檚 a question that an ex-colleague was asked during an interview with Big-G. The guy, a part from being a REALLY smart guy, is also very humble, and he doesn鈥檛 want to be mentioned by name. So, sorry for girls looking for a young, smart, promising young man: you need to find who he is yourself. ;) ...

January 7, 2010 路 7 min 路 1318 words