Ejercicios de Go

FizzBuzz in Go

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

  • Principiante
  • 3 min de lectura
  • 1 ejemplo ejecutable
Lo que aprenderás
  • 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.

Puntos clave

  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.

Ejemplo ejecutable de Go

Go
Ejecutar código →
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, " "))
}
Obtén un botón Run para este ejemplo Resultado de ejecutar el código
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Practica

Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.

¿Terminaste esta lección?

Márcala como aprendida para seguir tu progreso.

Siguiente: Loops with for →

Practica con un reto

Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.

Todos los retos