2021-09-24:给定一个正整数 n ,输出的第 n 项。前五项如下:1:1。2:11。3:21。4:1211。5:111221。第一项是数字 1 。描述前一项,这个数是 1 即 “ 一 个 1 ”,记作 "11"。描述前一项,这个数是 11 即 “ 二 个 1 ” ,记作 "21"。描述前一项,这个数是 21 即 “ 一 个 2 + 一 个 1 ” ,记作 "1211"。描述前一项,这个数是 1211 即 “ 一 个 1 + 一 个 2 + 二 个 1 ” ,记作 "111221"。返回第N项的字符串。

福大大 答案2021-09-24:

自然智慧。递归。

代码用golang编写。代码如下:

package main

import "fmt"

func main() {
    ret := countAndSay(5)
    fmt.Println(ret)
}

func countAndSay(n int) string {
    if n < 1 {
        return ""
    }
    if n == 1 {
        return "1"
    }
    last := countAndSay(n - 1)
    ans := make([]byte, 0)
    times := 1
    for i := 1; i < len(last); i++ {
        if last[i-1] == last[i] {
            times++
        } else {
            ans = append(ans, []byte(fmt.Sprintf("%d", times))...)
            ans = append(ans, []byte(fmt.Sprintf("%c", last[i-1]))...)
            times = 1
        }
    }
    ans = append(ans, []byte(fmt.Sprintf("%d", times))...)
    ans = append(ans, []byte(fmt.Sprintf("%c", last[len(last)-1]))...)
    return string(ans)
}

执行结果如下:
图片


左神java代码