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"
Or11
.
11
is read off as"two 1s"
Or21
.
21
is read off as"one 2
, thenone 1"
Or1211
.
Given an integer n, generate the nth sequence.
Note:the sequence of integers would be represented as a string.
title: The main number, but the title requirement is to output the nth string, that is, if you enter 5, the output string 111221.
Analysis: According to test instructions, you can first define two strings, one to represent the current cur, one to represent the next level to the first TMP, and then traverse each encounter the same to make count++, and then use the ' 0 ' +count to indicate that the number is several.
Full code:
#include <stdio.h> #include <stdlib.h> #include <string.h>char* countandsay (int n) { if (n==1) return "1"; char *cur= (char*) malloc (sizeof (char) * *), *tmp;cur[0]= ' 1 ', Cur[1]=0;int len,index,i,j,count;for (i=2;i< =n;i++) {len=strlen (cur); tmp= (char*) malloc (sizeof (char) * (3*len)); memset (Tmp,0,3*len); Count=1;for (index=1,j=0; index<len;index++) {if (cur[index]==cur[index-1]) count++;else{tmp[j++]= ' 0 ' +count;tmp[j++]=cur[index-1];count= 1;}} tmp[j++]= ' 0 ' +count;tmp[j++]=cur[len-1];free (cur); cur=tmp;} return cur;} int main () { int n; while (scanf ("%d", &n)!=eof) {printf ("%s\n", Countandsay (n)); } return 0;}
Leetcode 38th question-count and Say