在Golang中的Hackerrank楼梯挑战问题

huangapple go评论95阅读模式
英文:

hackerrank staircase challenge problem in Golang

问题

我想用GO语言解决Hackerrank上的这个挑战。当我运行代码时,得到的结果与挑战要求的结果相同,但他们不接受我的答案。
这是挑战链接:
https://www.hackerrank.com/challenges/staircase/problem?isFullScreen=true

这是我的代码:

func staircase(n int32) {
    var i int32
    for i = 0; i < n; i++ {
        fmt.Println(strings.Repeat(" ", int(n-i)), strings.Repeat("#", int(i)))
    }
}
英文:

I want to solve this challenge in hackerrank in GO. When I run it I get the same result as the challenge wants but they don't accept my answer.
Here is the challenge link:
https://www.hackerrank.com/challenges/staircase/problem?isFullScreen=true

Here is my code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

func staircase(n int32) {
	var i int32
	for i = 0; i &lt; n; i++ {
		fmt.Println(strings.Repeat(&quot; &quot;, int(n-i)), strings.Repeat(&quot;#&quot;, int(i)))

	}

}

<!-- end snippet -->

答案1

得分: 1

首先,第一行必须有一个 # 符号,而最后一行必须有 n# 符号。所以将循环改为从 1n(包括 n)。

其次,fmt.Println() 在参数之间打印一个空格,这会“扭曲”输出。要么将这两个字符串连接起来,要么使用 fmt.Print(),它不会在字符串参数之间添加空格,要么使用 fmt.Printf("%s%s\n", text1, text2)

例如:

func staircase(n int32) {
    for i := int32(1); i <= n; i++ {
        fmt.Println(strings.Repeat(" ", int(n-i)) + strings.Repeat("#", int(i)))
    }
}

使用 staircase(4) 进行测试,输出将会是(在 Go Playground 上试一试):

   #
  ##
 ###
####
英文:

First, the first line must have one # sign, and the last must have n # signs. So change the loop to go from 1 to n inclusive.

Next, fmt.Println() prints a space between arguments, which will "distort" the output. Either concatenate the 2 strings, or use fmt.Print() which does not add spaces between string arguments, or use fmt.Printf(&quot;%s%s\n&quot;, text1, text2).

For example:

func staircase(n int32) {
	for i := int32(1); i &lt;= n; i++ {
		fmt.Println(strings.Repeat(&quot; &quot;, int(n-i)) + strings.Repeat(&quot;#&quot;, int(i)))
	}
}

Testing it with staircase(4), output will be (try it on the Go Playground):

   #
  ##
 ###
####

huangapple
  • 本文由 发表于 2022年11月29日 16:44:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/74611260.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定