Jason's Blog

March 17, 2010

FizzBuzz test in C#

Filed under: programming — Tags: — Jason @ 9:55 pm

I’ve been looking at developer job related web sites to see what kinds of “things” are being used in interviews. There are a few programmer challenges that people are using to weed out the less capable developers. In particular the one called FizzBuzz test is quite amazing to me. It isn’t the simplicity of the challenge that gets me it is the fact that so many cannot write it during the interview. I would assume that any level of developer can easily complete this code. Although I keep seeing examples all over the web about how current (2010) job candidates cannot write it.

So, what the heck! Another example of how it can be done.

The challenge is to print all numbers from 1 to 100. When a number is divisible by 3 print “Fizz” instead. And when the number is divisible by 5 print “Buzz” instead. Lastly print “Fizz-Buzz” if the number is divisible by both 3 and 5.

void Main()
{
    Console.WriteLine(
        Enumerable.Range(1, 100)
            .Aggregate(new StringBuilder(), (sb, i) => sb.AppendLine(fizzBuzz(i)))
            .ToString());
}

string fizzBuzz(int i)
{
    var isRule3 = i % 3 == 0;
    var isRule5 = i % 5 == 0;

    if(isRule3 && isRule5) return "Fizz-Buzz";
    if(isRule3) return "Fizz";
    if(isRule5) return "Buzz";
    return i.ToString();
}
Advertisements

1 Comment »

  1. public string FizzOrBuzz(int number)
    {
    var answer=””;

    if ((number % 3 == 0)) answer = “Fizz”;

    if ((number % 5 == 0)) return answer + “Buzz”;

    return string.IsNullOrEmpty(answer) ? number.ToString() : answer;
    }

    Comment by anthony — September 19, 2010 @ 12:52 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: