基础算法-Fizz Buzz

Fizz Buzz
  • 如果 n 是3的倍数,输出"Fizz",如果 n 是5的倍数,输出“Buzz".如果 n 同时是3和5的倍数,输出 "FizzBuzz"
function fizzBuzz(int $n): array
{
    $result = [];
    //初始化为数字
    for ($i = 1; $i <= $n; $i++) {
        $result[$i] = "";
    }
    //如果是3的倍数,改为Fizz
    for ($i = 2; $i < $n; $i += 3) {
        $result[$i] = "Fizz";
    }
    //如果是5的倍数,改为Buzz
    for ($i = 4; $i < $n; $i += 5) {
        $result[$i] = "Buzz";
    }
    //如果是3和5的倍数,也就是15倍改为FizzBuzz
    for ($i = 14; $i < $n; $i += 15) {
        $result[$i] = "FizzBuzz";
    }
    return $result;
}

  • 运行结果
array:15 [▼
  1 => ""
  2 => "Fizz"
  3 => ""
  4 => "Buzz"
  5 => "Fizz"
  6 => ""
  7 => ""
  8 => "Fizz"
  9 => "Buzz"
  10 => ""
  11 => "Fizz"
  12 => ""
  13 => ""
  14 => "FizzBuzz"
  15 => ""
]
posted @ 2021-04-20 11:46  惊风破浪的博客  阅读(2)  评论(0编辑  收藏