Writing FizzBuzz

后端 未结 30 2130
庸人自扰
庸人自扰 2020-12-04 08:50

Reading the coding horror, I just came across the FizzBuzz another time.

The original post is here: Coding Horror: Why Can\'t Programmers.. Program?

For thos

30条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 09:33

    Ok, what the heck, here's the solution I've come to like :)

    public void DoFizzBuzz()
    {
        for (int i = 1; i <= 100; ++i)
        {
            bool isDivisibleByThree = i % 3 == 0;
            bool isDivisibleByFive = i % 5 == 0;
    
            if (isDivisibleByThree || isDivisibleByFive)
            {
                if (isDivisibleByThree)
                    cout << "Fizz";
    
                if (isDivisibleByFive)
                    cout << "Buzz";
            }
            else
            {
                cout << i;
            }
            cout << endl;
        }
    }
    

    Obviously, this is not the fastest solution, but I like it because it emphasizes readability and makes the "FizzBuzz" case no longer a special case, but something that will happen naturally through the code path.

    In the end, what I love most about this question whenever it comes up is that we get to see just how many different solutions ppl can come up with.

提交回复
热议问题