Take any number you like.

Pronounce the number correctly. As for the number 1, It must be read as "one 1," where “one” represents the total digits of that number.
Now write the "one 1" numerically. So we get the number 11.
Next we can read 11 as "two 1." So the next number of this sequence is 21.
Apply the same method for finding the next number of the sequence.
The starting number may be any number you want.
This sequence grows indefinitely.
Only for same digits of number like 22, if you apply the above method , this will return the same result 22 instead of a sequence.
Only the digits 1, 2, and 3 are the members of this sequence. There must not be any other number.

1

11

21

1211

111221

312211

13112221

1113213211

31131211131221

13211311123113112211

11131221133112132113212221

3113112221232112111312211312113211

1321132132111213122112311311222113111221131221

11131221131211131231121113112221121321132132211331222113112211

311311222113111231131112132112311321322112111312211312111322212311322113212222

public String countAndSay(int n) {
   StringBuilder sb=new StringBuilder("1");
   //converting to string builder 
    while(--n>0){
        StringBuilder nt= new StringBuilder();
        for(int i=0;i<sb.length();++i){
            int c=1;
			//check that prevoius and the current character elemnt have same value
			//if yes then add +1 to its frequency
            while(i+1<sb.length() && sb.charAt(i)==sb.charAt(i+1)){
            ++c;
                ++i;
            }
        
        nt.append(c).append(sb.charAt(i));
    }
    sb=nt;
}
    return sb.toString();
}
Comments (0)