I had this as an interview question, and the interviewer pointed this out. Here's what I wrote:
//C# Syntax here
public string Reverse(string s)
{
char[] arr = s.ToCharArray();
int idx = 0;
int endIdx = s.Length - 1;
for(; idx < endIdx; ++idx, --endIdx)
{
char temp = arr[idx];
arr[idx] = arr[endIdx];
arr[endIdx] = temp;
}
return arr.ToString();
}
However, the interviewer was asking if I should have changed it to this:
//C# Syntax here
public string Reverse(string s)
{
char[] arr = s.ToCharArray();
int idx = 0;
int endIdx = s.Length - 1;
while(idx < endIdx)
{
char temp = arr[idx];
arr[idx] = arr[endIdx];
arr[endIdx] = temp;
++idx;
--endIdx;
}
return arr.ToString();
}
Personally, I like the first version, because it puts all of the machinery which controls the loop into the loop statement. One can insert continue
or break
or return
statements into the loop without it breaking things.
However, some programmers dislike putting that stuff into the for
, because they think it's being too "clever".
What do you consider best-practice for this?