I could only do this with String, for example:
String str = "";
for (int i = 0; i < 100; i++) {
str = i + str;
}
Is there a way to achieve this with StringBuilder? Thanks.
// DO NOT DO THIS. It is quadratic-time!
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):
StringBuilder
.StringBuilder
when you're done.This will turn an O(n²) solution into O(n).