Follow me on Twitter RSS FEED

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...

12 comments:

Anonymous said...

good..thnx

Anonymous said...

Please explain this logic..

Unknown said...

Works on this logic:
(A XOR B) XOR B = A
(A XOR B) XOR A = B

Surendar N said...

Thanks Luke!

Consider you want to swap A and B without using temp variable using + and - operator.

A=(A+B)-A
B=(A+B)-B

Same case here in xor also as mentioned by LUKE!

Naresh Pirati said...

good logic every one must learn

Anonymous said...

arent start and end temp variables??

Ronak Kosamia said...

let's say we want to switch 2 binary values x1 = 100 and x2 = 111 so that x1 = 111 and x2 = 100.


in c# x1 ^= x2 equals to x1 = x1 ^ x2 where ^ is the bitwise XOR.



XOR (Exclusive OR) table
0 XOR 0 = 0
0 XOR 1 = 1
1 XOR 0 = 1
1 XOR 1 = 0
First operation: x1 = x1 XOR x2

x1: 1 0 0
x2: 1 1 1
New x1: 0 1 1

Second operation x2 = x2 XOR x1

x1: 0 1 1
x2: 1 1 1
New x2: 1 0 0

Third operation: x1 = x1 XOR x2

x1: 0 1 1
x2: 1 0 0
New x1: 1 1 1


And voila, we now have x1 = 111 and x2 = 100.
and for each pair in array we do this because string chars are in essence binary values :)))
This method is also the quickest way to reverse a string.
Recursive way is almost 4-5 times slower.

hitesh kumar said...

C++ Program to Reverse a Strings

Reverse a String means reverse the position of all character of String. You can use swapping concept to reverse any string in c++.

Unknown said...

can any one explain above logic bit by bit?.. swapping

brahbequi-he said...

brahbequi-he Dana Head https://wakelet.com/wake/Z8ijPRFCDUgGrsirp6pFt
tawarmidisch

venteYicro-2000 said...

WmanreaXcent-ne Megan Davis Eset NOD 32
Emsisoft Anti-Malware
SONY Vegas
giosmaretun

Npulchvecred-za said...

climmoXitga Candy Mizeur there
Awesome
paxwadaloug

Post a Comment