Go 練習問題

FizzBuzz in Go

The classic interview warm-up, solved with a switch.

  • 初級
  • 約3分で読めます
  • 実行できるサンプル 1 件
学べること
  • switch without a value
  • Order of the cases
  • strings.Join
1 to 6
11
22
Fizz3
44
Buzz5
Fizz6

Check 15 first

Print the numbers from 1 to 15, but print Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both.

A switch without a value runs the first case that is true, so the check for 15 must come first. strconv.Itoa turns a number into a string, and strings.Join puts the words on one line.

重要なポイント

  1. The first true case runs.
  2. n%15 must come before n%3 and n%5.
  3. strconv.Itoa turns a number into text.

実行できる Go のサンプル

Go
コードを実行 →
main.go
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func fizzbuzz(n int) string {
	switch {
	case n%15 == 0:
		return "FizzBuzz"
	case n%3 == 0:
		return "Fizz"
	case n%5 == 0:
		return "Buzz"
	default:
		return strconv.Itoa(n)
	}
}

func main() {
	words := make([]string, 0, 15)
	for n := 1; n <= 15; n++ {
		words = append(words, fizzbuzz(n))
	}
	fmt.Println(strings.Join(words, " "))
}
この例の実行ボタンを作成 実行結果
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

練習

サンプルをオンラインコンパイラーで開き、値を変えたり行を追加したりして、実行する前に出力を予想してみましょう。次に、わざとコードを壊してコンパイラーのメッセージを読んでみてください。

このレッスンを終えましたか?

学習済みにすると進み具合を記録できます。

次へ: Loops with for →

チャレンジで練習する

このレッスンの内容を使って実際の問題を解きましょう。各チャレンジはブラウザで動き、すぐにテストされ、AI のレビューも受けられます。

すべてのチャレンジ