Reverse a String without Using a Temporary Variable

The bitwise XOR operator can be used to swap two variables. The XOR of two numbers x and y returns a number which has all the bits as 1 wherever bits of x and y differ. For example XOR of 10 (In Binary 1010) and 5 (In Binary 0101) is 1111 and XOR of 7 (0111) and 5 (0101) is (0010).

[code language=”cpp”]
#include <stdio.h>
int main()
{
int x = 10, y = 5;

// Code to swap ‘x’ (1010) and ‘y’ (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)

printf("After Swapping: x = %d, y = %d", x, y);

return 0;
}
[/code]

The final code would look something like this –

[code language=”cpp”]
// C++ Program to reverse a string without
// using temp variable
#include <bits/stdc++.h>
using namespace std;

// Function to reverse string and return revesed string
string reversingString(string str, int start, int end)
{
// Iterate loop upto start not equal to end
while (start < end)
{
// XOR for swapping the variable
str[start] ^= str[end];
str[end] ^= str[start];
str[start] ^= str[end];

++start;
–end;
}
return str;
}

// Driver Code
int main()
{
string s = "GeeksforGeeks";
cout << reversingString(s, 0, 12);
return 0;
}
[/code]

3 comments on “Reverse a String without Using a Temporary Variable”


  • Adithya

    #include
    #include

    int main()
    {
    char s[20];
    scanf(“%s”,s);
    //char s1[20];
    int n=strlen(s);
    for(int i=n-1; i>=0; i–)
    {
    printf(“%c”,s[i]);
    }
    return 0;
    }