I read an interesting article about
Guerilla Interview this afternoon.. Which prompted me to check if I could still write some half-decent C, like reversing linked lists or detecting loops in a tree, as mentioned in this article.
That didn't go that well :] Anyway, at some point I stumbled upon a nice string reversing function. Some of you may find it interesting.
char* rev(char* str) {
int end = strlen(str) - 1;
int start = 0;
while (start < end) {
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];
++start;
--end;
}
return str;
}
The logic behind this being :
Let A = x and B = y.
So,
A = A XOR B
then A = x XOR y
B = y
B = A XOR B
then A = x XOR y
B = (x XOR y) XOR y
= x XOR (y XOR y)
= x
A = A XOR B
then A = (x XOR y) XOR x
= (y XOR x) XOR x
= y XOR (x XOR x)
= y
now B = x and A = y
Source:
http://discuss.fogcreek.com/techInterview/default.asp?cmd=show&ixPost=2077