java: use StringBuilder to insert at the beginning

前端 未结 9 1932
佛祖请我去吃肉
佛祖请我去吃肉 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:11

    How about:

    StringBuilder builder = new StringBuilder();
    for(int i=99;i>=0;i--){
        builder.append(Integer.toString(i));
    }
    builder.toString();
    

    OR

    StringBuilder builder = new StringBuilder();
    for(int i=0;i<100;i++){
      builder.insert(0, Integer.toString(i));
    }
    builder.toString();
    

    But with this, you are making the operation O(N^2) instead of O(N).

    Snippet from java docs:

    Inserts the string representation of the Object argument into this character sequence. The overall effect is exactly as if the second argument were converted to a string by the method String.valueOf(Object), and the characters of that string were then inserted into this character sequence at the indicated offset.

提交回复
热议问题