3 ms·
I agree with you, and for the record, I was only approaching this as one developer (out of several) doing an interview. It's just that, after several iterations
by msluyter 14y ago
I agree with you, and for the record, I was only approaching this as one developer (out of several) doing an interview. It's just that, after several iterations of, 1. "Hey Mike, can you interview this guy tomorrow" 2. Looks at resume, sees dozens of acronyms, languages, platforms 3. "Ok, can you write a function to reverse a string?" and getting something like 4:
for (int i = s.length() - 1; i >= 0; i--) {
String newString = new String();
char x = s.charAt(i);
newString = newString + x;
}
Well.... you get pretty jaded.
- whichdan 14y agoOut 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!