I have a question to find the N th number in the sequence.
1 11 21 1211 111221 312211 13112221 1113213211
The next number is obtained by saying out loud the number of digits in the previous number.
eg. inital number =1
next number = One 1 = 11
next number = Two 1 = 21
next number = One 2 and One 1 = 1211
Here is my code for getting next number:
private static void nextSequence(int N){
int i=1;
StringBuffer current = new StringBuffer(); // to populate current number
StringBuffer last = new StringBuffer(); // to populate next number
System.out.println("1");
// populate next number in sequence
current.append(1);
current.append(1);
while(i<=N){
int begin=1; // pointer to next index
int start=0; // pointer to start index
int count=1; // count the number of repeats
int j=1; // counts the length of characters counted
while(j<current.length()){
if(current.charAt(begin)==current.charAt(start)){
count++; // count the repeats between start and begin
}else{
last.append(count);
last.append(current.charAt(start));
start=begin;
count=1;
}
begin++;
j++;
}
last.append(count);
last.append(current.charAt(start));
System.out.println(last);
current=last;
last = new StringBuffer(); // reset the next seq numbe
i++;
}
}
Is this the correct approach? I am able to generate the said sequence, but I am not sure if this is the most efficient. Could you please help me correct if my I made any mistakes?