3 ms·
1. `char tmp( rev[i] );` is valid C++, but not C. 2. Your for() loop is still dividing `iLen/2` every iteration. Presumably the compiler would hoist the divisi
by cpeterso 16y ago
1. `char tmp( rev[i] );` is valid C++, but not C.
2. Your for() loop is still dividing `iLen/2` every iteration. Presumably the compiler would hoist the division out of the loop, but the code would still add some cognitive friction to future readers of this function. :)
Here's my attempt:
void strrev(char* s)
{
char* a = s;
char* z = s + strlen(s) - 1;
while (a < z)
{
const char c = *a;
*a = *z;
*z = c;
a++;
z--;
}
}
- palish 16y agoSurely that's less clear than "Swap( rev[i], rev[iLen - 1 - i] );"? And yes, the compiler would optimize out "iLen / 2", computing it once rather than every iteration.
- watmough 16y agoThis is the one I like. :D I have interviewed people, but I gave up asking coding questions, since no one could ever do them. And if you keep thumbs-downing people, you don't really get invited to interview any more people. Thanks again!