英文:
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 < n; i++ {
fmt.Println(strings.Repeat(" ", int(n-i)), strings.Repeat("#", int(i)))
}
}
<!-- end snippet -->
答案1
得分: 1
首先,第一行必须有一个 #
符号,而最后一行必须有 n
个 #
符号。所以将循环改为从 1
到 n
(包括 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("%s%s\n", text1, text2)
.
For example:
func staircase(n int32) {
for i := int32(1); i <= n; i++ {
fmt.Println(strings.Repeat(" ", int(n-i)) + strings.Repeat("#", int(i)))
}
}
Testing it with staircase(4)
, output will be (try it on the Go Playground):
#
##
###
####
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论