Count And Say

The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, ...

1 is read off as one 1 or 11. 11 is read off as two 1s or 21.

21 is read off as one 2, then one 1 or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

Example:

if n = 2, the sequence is 11.

public class Solution {
    public String countAndSay(int A) {
        int count = 1;
        String ans = "1";
        while (count < A) {
            String temp = "";
            for (int i = 0; i < ans.length(); i++) {
                int c = 1;
                char ch = ans.charAt(i);
                while (i + 1 < ans.length() && ch == ans.charAt(i + 1)) {
                    i++;
                    c++;
                }
                char num = (char) (c + '0');
                temp = temp + num + ch;
            }
            ans = temp;
            count++;
        }
        return ans;
    }
}

Last updated