nth
element of the Look and Say sequence.
Look and Say sequence:
Starting with 1, the nth
element of the sequence is generated by reading off the digits of the (n -1)th
element, counting the number of digits in groups of the same digit.
Example:
Input : 5 Output : 111221
public static String lookAndSay(int sequenceNumber) { if (sequenceNumber <= 0) return null; String output = "1"; int i = 1; while (i < sequenceNumber) { StringBuilder stringBuilder = new StringBuilder(); int count = 1; for (int j = 1; j < output.length(); j++) { if (output.charAt(j) == output.charAt(j - 1)) { count++; } else { stringBuilder.append(count); stringBuilder.append(output.charAt(j - 1)); count = 1; } } stringBuilder.append(count); stringBuilder.append(output.charAt(output.length() - 1)); output = stringBuilder.toString(); i++; } return output; }
C
Java
Python