StringBuilder Performance
Completed
Read n (≤ 20000) and build the string 0,1,2,...,n-1 with a StringBuilder. Print its length and its last 10 characters.
Input
One integer ≥ 10.
Output
Two lines.
Example
Input
10
Output
19 ,5,6,7,8,9
Editor
Java
Hints
Repeated String + in a loop copies the whole string each time (O(n²)).
Solution explanation
StringBuilder appends in amortised constant time, so building large text stays fast.
Show solution
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
if (i > 0) sb.append(',');
sb.append(i);
}
System.out.println(sb.length());
System.out.println(sb.substring(sb.length() - 10));
}
}