In the last post, we have seen an effective algorithm to multiply a number by 7. In this post we shall see about an effective algorithm to reverse a string. This is a classic interview question and well expect this question in your technical interview even at google, microsoft, yahoo, etc.
In this algorithm, the interviewer mainly notices that is your algorithm inplace (i.e) can it do without using any extra memory? Thus we shall find a way to reverse a string without using additional string. The algorithm is given below.
Step 1: i = 0; j = length of string - 1
Step 2: swap string[i] and string [j]
Step 3: increment i and decrement j
Step 4: Go to step 2 if i < j
Thus a C++ code to reverse a C style string is given below:
void strrev(char *str)
{
int n= strlen(str);
for(int i = 0, j = n-1; i < j; i++,j--)
{
//swap a[i] and a[j]
a[i] = a[i] ^ a[j];
a[j] = a[i] ^ a[j];
a[i] = a[i] ^ a[j];
}
}
In this algorithm, the interviewer mainly notices that is your algorithm inplace (i.e) can it do without using any extra memory? Thus we shall find a way to reverse a string without using additional string. The algorithm is given below.
Step 1: i = 0; j = length of string - 1
Step 2: swap string[i] and string [j]
Step 3: increment i and decrement j
Step 4: Go to step 2 if i < j
Thus a C++ code to reverse a C style string is given below:
void strrev(char *str)
{
int n= strlen(str);
for(int i = 0, j = n-1; i < j; i++,j--)
{
//swap a[i] and a[j]
a[i] = a[i] ^ a[j];
a[j] = a[i] ^ a[j];
a[i] = a[i] ^ a[j];
}
}