4 ms·
Out of curiosity - is there something particularly wrong with that code, or is it just nauseating reading the same thing over and over?
by whichdan 14y ago
Out of curiosity - is there something particularly wrong with that code, or is it just nauseating reading the same thing over and over?
- qwertyz 14y agonewString is initialized inside the loop, so it will get destroyed when you exit the loop.
- S4M 14y agoHe should instanciate newString outside of the loop, I guess.
- msluyter 14y ago1.) newString gets re-created every iteration of the loop, so it always contains a single character, and at the end of the loop it contains the first character of the string. 2.) Strings are immutable (in Java), so "newString = newString + x" creates a new object on every iteration. Better to use a StringBuffer and swap the ith and N - i - 1th characters of the string.
- rhizome 14y agoIsn't there some common library that contains a reverse() String method? That's why I like Ruby, for stuff like "string".reverse in the standard library. I can just use the language and know that the people writing the language are better language() method implementors than I am, which is fine. Not sure how well that flies in interviews at KPMG, but whatever.
- whichdan 14y agoWow, I completely glossed over that. I also don't write Java, so that's an interesting bit of info. Thanks!