Go语言版本:
- package main
- import (
- "fmt"
- "strings"
- )
- func main() {
- fmt.Println("10")
- printStarTree(10)
- fmt.Println("9")
- printStarTree(9)
- }
- func printStarTree(n int) {
- // Calculate the max number of padded spaces on the left
- spaceCount := (n - 1) / 2
- var padBuilder strings.Builder
- for j := 0; j < spaceCount; j++ {
- padBuilder.WriteRune(' ')
- }
- padding := padBuilder.String()
- // This string builder is used to accumulate the stars
- var starBuilder strings.Builder
- starBuilder.WriteRune('*')
- // In each iteration, the padding contracts and the stars expand
- for i := 1; i <= n; i += 2 {
- // Print padding + stars
- fmt.Println(padding[:spaceCount] + starBuilder.String())
- // Stars increase at the rate of two per row
- starBuilder.WriteString("**")
- // Reduce padding for the next row
- spaceCount--
- }
- }
复制代码 |