未分類

Fizz Buzz

Fizz Buzz

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

For Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

Default:

1
2
3
func fizzBuzz(n int) []string {
}

解答思路:

這題相當的讓我印象深刻,不外乎是朋友應徵資深工作而面試卻出了這麼一題,不論是資料分析的工作還是網頁的工作都有人碰到,總之這題就是給予1~n,當該數同時為3與5的倍數時,回傳FizzBuzz,若只是3的倍數則回傳Fizz,而若只是5的倍數則回傳Buzz,初次學習程式語言的人應該都有碰過類似的題目。

程式碼解說:

首先先宣告一空陣列字串,接著就開始從1~n遍歷,當該數同時為3與5的倍數時(餘數為0),插入FizzBuzz,你也可以直接寫15的倍數,而若只是3的倍數則插入Fizz,而若只是5的倍數則插入Buzz,如果上述的情況都不是的話則將該數轉為該數的字串並插入,最後在遍歷結束後回傳整個結果。

1
2
3
4
5
6
7
8
9
10
11
12
13
var result []string
for i := 1; i <= n; i++ {
if i%3 == 0 && i%5 == 0 {
result = append(result, "FizzBuzz")
} else if i%3 == 0 {
result = append(result, "Fizz")
} else if i%5 == 0 {
result = append(result, "Buzz")
} else {
result = append(result, strconv.Itoa(i))
}
}
return result

完整程式碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func fizzBuzz(n int) []string {
var result []string
for i := 1; i <= n; i++ {
if i%3 == 0 && i%5 == 0 {
result = append(result, "FizzBuzz")
} else if i%3 == 0 {
result = append(result, "Fizz")
} else if i%5 == 0 {
result = append(result, "Buzz")
} else {
result = append(result, strconv.Itoa(i))
}
}
return result
}

總結:

Fizz Buzz是給予1~n,當該數同時為3與5的倍數時,回傳FizzBuzz,若只是3的倍數則回傳Fizz,而若只是5的倍數則回傳Buzz。

分享到