编写一个程序,用字符串表示数字 1 到 n,其中:
- 如果数字是3的倍数,则输出Fizz
- 如果数字是5的倍数,则输出Buzz
- 如果数字是3和5的倍数,则输出FizzBuzz
原题
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”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
实现
实现一
1func fizzBuzz(n int) []string {
2 ret := make([]string, n)
3
4 for i := 1; i <= n; i++ {
5 if i%15 == 0 {
6 ret[i-1] = "FizzBuzz"
7 } else if i%5 == 0 {
8 ret[i-1] = "Buzz"
9 } else if i%3 == 0 {
10 ret[i-1] = "Fizz"
11 } else {
12 ret[i-1] = strconv.Itoa(i)
13 }
14 }
15
16 return ret
17}
实现二
1func fizzBuzz(n int) []string {
2 ret := make([]string, n)
3 three := 3
4 five := 5
5 fifteen := 15
6
7 for i := 1; i <= n; i++ {
8 if i == fifteen {
9 ret[i-1] = "FizzBuzz"
10 fifteen += 15
11 five += 5
12 three += 3
13 } else if i == five {
14 ret[i-1] = "Buzz"
15 five += 5
16 } else if i == three {
17 ret[i-1] = "Fizz"
18 three += 3
19 } else {
20 ret[i-1] = strconv.Itoa(i)
21 }
22 }
23
24 return ret
25}
经过测试,两个版本的性能差不多。