Question
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.
My C# Solution
public class Solution {
public string CountAndSay(int n) {
var result = "1";
if (n == 1) return result;
var i = 1;
var countSay = 1;
while (i < n)
{
var temp = result;
result = string.Empty;
for (var j = 0; j < temp.Length - 1; j++)
{
if (temp[j] == temp[j + 1])
{
countSay++;
}
else
{
result += countSay;
result += temp[j];
countSay = 1;
}
}
result += countSay;
result += temp[temp.Length - 1];
countSay = 1;
i++;
}
return result;
}
}