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 리뷰를 받을 수 있습니다.

모든 챌린지