[用Golang刷LeetCode之 10] 412. Fizz Buzz

miltonsun · · 1013 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

题目

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)
    }
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:miltonsun

查看原文:[用Golang刷LeetCode之 10] 412. Fizz Buzz

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1013 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传