java: use StringBuilder to insert at the beginning
you can use strbuilder.insert(0,i);
Maybe I'm missing something but you want to wind up with a String that looks like this, "999897969594...543210"
, correct?
StringBuilder sb = new StringBuilder();
for(int i=99;i>=0;i--){
sb.append(String.valueOf(i));
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<100;i++){
sb.insert(0, Integer.toString(i));
}
Warning: It defeats the purpose of StringBuilder
, but it does what you asked.
Better technique (although still not ideal):
- Reverse each string you want to insert.
- Append each string to a
StringBuilder
. - Reverse the entire
StringBuilder
when you're done.
This will turn an O(n²) solution into O(n).