Follow me on Twitter RSS FEED
Showing posts with label Reverse String. Show all posts
Showing posts with label Reverse String. Show all posts

Reverse String using XOR and without using Temporary Variable

Posted in
My friend faced this question for TCS technical interview. The code the much simple but the logic is bit complex

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 the above version is with while loop even one can use for loop instead of it.

XOR (Exclusive OR) table
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
So how does it works.

First operation:x1 = x1 XOR x2
x1:100
x2:111
New x1:011
Second operationx2 = x2 XOR x1
x1:011
x2:111
New x2:100
Third operation:x1 = x1 XOR x2
x1:011
x2:100
New x1:111


So finally we have done X1 and X2 are swapped. This method is for both without using Temporary variable and also using Xor operator...

Pretty Cool huh...