37. 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.
---
The test case in LeetCode seems not right.
I am not sure this is an correct solution. ^^
---
public static String countAndSay(int n) { StringBuffer sb = new StringBuffer(); int div = 1; while (n / div >= 10) { div *= 10; } int last = -1; int count = 0; while (n > 0) { int val = n / div; if(last == -1){ last = val; count = 1; }else if (val == last) count++; else { sb.append(count); sb.append(last); count = 1; last = val; } n -= div * val; div /= 10; } sb.append(count); sb.append(last); return sb.toString(); }
浙公网安备 33010602011771号