แบบฝึกหัด Go
FizzBuzz in Go
The classic interview warm-up, solved with a switch.
สิ่งที่คุณจะได้เรียนรู้
- 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.
ประเด็นสำคัญ
- The first true case runs.
- n%15 must come before n%3 and n%5.
strconv.Itoaturns a number into text.
ตัวอย่าง 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ฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
โจทย์ทั้งหมด