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.
Subscribe to see which companies asked this question
public class Solution {
public String countAndSay(int n) {
char sayWhat ='1';
int sayMuch = 0;
int count =1;
String ret = "1";
while(count<n){
String tmp = ret;
String get ="";
count++;
for(int i=0;i<tmp.length();i++){
if(sayWhat==tmp.charAt(i)){
sayMuch++;
}else{
get+=String.valueOf(sayMuch)+sayWhat;
sayWhat=tmp.charAt(i);
sayMuch=1;
}
}
get+=String.valueOf(sayMuch)+sayWhat;
ret = get;
sayMuch=0;
sayWhat=ret.charAt(0);
}
return ret;
}
}