Reverse string without using any temporary variable

link 0

We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable.

Examples:

Input  : str = "abc"
Output : str = "cba" 

Input :  str = "techcodebit"
Output : str = "tibedochcet"

If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable. Below is C++ implementation of the idea.

// 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 = "techcodebit";
    cout << reversingString(s, 0, 12);
    return 0;
}

Output:

 tibedochcet

If we are allowed to library function, We don’t even need indexes of first and last characters.

// Reversing a string using reverse()
#include<bits/stdc++.h>
using namespace std;
int main()
{
   string str = "techcodebit";
    
   // Reverse str[beign..end]
   reverse(str.begin(), str.end());
    
   cout << str;
   return 0;
}

Output:

tibedochcet

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits:http://www.geeksforgeeks.org/reverse-string-without-using-any-temporary-variable/
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar