LoginSignup
2
2

More than 5 years have passed since last update.

PHPでfizzbuzz問題にトライした話

Last updated at Posted at 2015-06-01

縛り

  • PHPで書く
  • 剰余は使わない

トライ

3の倍数

  • 3の倍数は数値のそれぞれの位を足しても3の倍数になるので、9より小さくなるまで足し算を繰り返す
  • 3, 6, 9 のいずれかにマッチすれば Fizz

5の倍数

  • 5の倍数は1の位が必ず0か5になるはず
  • 0, 5にマッチすれば Buzz

ソースコード

fizzbuzz.php

<?php

for($num = 1; $num <= 100; $num++) {
    $flag = false;
    $sum = $num;
    while($sum > 9) {
        $sum = array_sum(array_map('intval', str_split((string)$sum, 1)));
    }
    if(in_array($sum, array(3, 6, 9), true)) { $flag = true; echo 'fizz'; }
    if(in_array(substr((string)$num, -1), array('0', '5'), true)) { $flag = true; echo 'buzz'; }
    if(!$flag) echo $num;
    echo "\n";
}

振り返り

  • 型指定を厳密にやったら $sum の計算が気持ち悪いことになった。
  • array_sumは内部の計算で動的に型を変換してるようだ。気持ち悪い・・・
  • ループの頭で変数初期化するの無駄感ある。特に $flag
2
2
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
2
2