Posted in
C++,
Reverse String
My friend faced this question for TCS technical interview. The code the much simple but the logic is bit complex
So how does it works.
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 |
| 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 |
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...

