0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GoでFIZZBUZZを解く

Last updated at Posted at 2025-06-18

勉強がてらGo言語でFIZZBUZZ問題を解いてみました。

最初は一の位に着目してFIZZBUZZの出力判定をしてみようとしか考えていませんでした。
それが書いている内にせっかくだし色々と捻ってみようと方向転換したのが運の尽き。
最終的に我ながらよく分からないことをやってるなぁと感じる出来になってしまいました。

main.go
package main

import (
    sc "strconv"
    f "fmt"
    m "math"
)

const (
    FIZZ = "3692581470"
    BUZZ = "50"
)

type fizzBuzz struct {
    FCnt int
    BCnt int
}

// 出力する文字列の取得
func (fb *fizzBuzz)getFizzBuzz(num int) string {
    ret := sc.Itoa(num)

    // 次にFIZZを出力する値を求める
    fNum, _ := sc.Atoi(sc.Itoa((fb.FCnt - num / 31) / 3) + string(FIZZ[fb.FCnt % 10]))
    // 次にBUZZを出力する値を求める
    bNum, _ := sc.Atoi(sc.Itoa(fb.BCnt / 2 + fb.BCnt % 2) + string(BUZZ[fb.BCnt % 2]))

    // 引数が上で求めた値の場合、FIZZを出力文字列に追加する
    if  num == fNum {
        ret += "FIZZ"
        fb.FCnt++
    }

    // 引数が上で求めた値の場合、BUZZを出力文字列に追加する
    if num == bNum {
        ret += "BUZZ"
        fb.BCnt++
    }

    // 数字のみの場合はそのまま、そうでなければ数字部分を除外した文字列を返却する
    sub := len(ret) - len(sc.Itoa(num))
    return ret[sub >> int(m.Logb(float64(sub + 1))) * len(sc.Itoa(num)):]
}

func main(){
    var fb fizzBuzz
    for i := 1; i <= 100; i++ {
        f.Println(fb.getFizzBuzz(i))
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?