题目
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”
]
代码
fizzBuzz.go
package _412_Fizz_Buzz
import "strconv"
func FizzBuzz(n int) []string {
var ret []string
var i int
for i = 1; i <= n; i++ {
if 0 == i % 15 {
ret = append(ret, "FizzBuzz")
} else if 0 == i % 3 {
ret = append(ret, "Fizz")
} else if 0 == i % 5 {
ret = append(ret, "Buzz")
} else {
ret = append(ret, strconv.Itoa(i))
}
}
return ret
}
测试
fizzBuzz_test.go
package _412_Fizz_Buzz
import "testing"
func arrayStringEqual(want, ret []string) bool {
len1 := len(want)
len2 := len(ret)
if len1 != len2 {
return false
}
for i := 0; i < len1; i++ {
if want[i] != ret[i] {
return false
}
}
return true
}
func TestFizzBuzz(t *testing.T) {
input := 15
want := []string{"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"}
ret := FizzBuzz(input)
equal := arrayStringEqual(want, ret)
if equal {
t.Logf("pass")
} else {
t.Errorf("fail, want %+v, get %+v", want, ret)
}
}