-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountAndSay.java
More file actions
69 lines (65 loc) · 1.78 KB
/
Copy pathCountAndSay.java
File metadata and controls
69 lines (65 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* 420. Count and Say
* 中文English
* 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.
*
* Example
* Example 1:
*
* Input: 1
* Output: "1"
* Example 2:
*
* Input: 5
* Output: "111221"
* Notice
* The sequence of integers will be represented as a string.
*/
public class CountAndSay {
public static void main(String args[]){
System.out.println("Hello Count And Say");
System.out.println(countAndSay(11));
}
public static String countAndSay(int n){
StringBuffer outputBuf = new StringBuffer();
String output;
if(n == 1){
output = "1";
return output;
}else if(n == 2){
output = "11";
return output;
}else{
String str = countAndSay(n-1);
char []charArr = str.toCharArray();
int number = charArr[0] - 48;
int count = 1;
int i = 1;
while(i<charArr.length){
if(charArr[i] == charArr[i-1]){ // if current value was the same with the last one
count ++;
}else{
outputBuf.append(Integer.toString(count));
outputBuf.append(Integer.toString(number));
number = charArr[i] -48;
count = 1;
}
i++;
}
outputBuf.append(Integer.toString(count));
outputBuf.append(Integer.toString(number));
output = outputBuf.toString();
return output;
}
}
}