java: use StringBuilder to insert at the beginning

前端 未结 9 2123
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-30 03:55

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 wit

9条回答
  •  臣服心动
    2021-01-30 04:17

    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):

    1. Reverse each string you want to insert.
    2. Append each string to a StringBuilder.
    3. Reverse the entire StringBuilder when you're done.

    This will turn an O(n²) solution into O(n).

提交回复
热议问题