(no subject)

Apr 07, 2009 10:01

In the interview for my last job I was asked to write a solution to the FizzBuzz test. The test is to see how you think about code and whether you have a logical approach to writing it.

The brief is to write code to print each number from 1 to 100 and for each of those numbers write "Fizz" for those divisible by 3, "Buzz" for those divisible by 5 and "FizzBuzz" for those divisible by both 3 and 5.

My C# was a little "rusty" at the time (actually I'd hardly done any!) so I came up with:

for(int i;i<=100;i++)
  {
    string out = i + ": ";
    if (i%3==0)
      {
        out += "Fizz";
      }
    if (i%5==0)
      {
        out += "Buzz";
      }
    Console.WriteLine(out);
  }

Now, having somewhat greater experience of C#, the clearly obvious way of writing the code is like this:

for(int i;i<=100;i++) Console.WriteLine(string.Format("{0}: {1}{2}", i, i%3==0?"Fizz":"", i%5==0?"Buzz":""))
Previous post Next post
Up