Tuesday, February 1, 2011

Two C# Solutions for the FizzBuzz Problem

In case you are interested...

namespace FizzBuzz
{
class Program
{
static void Main(string[] args)
{
const string fizz = "FIZZ";
const string buzz = "BUZZ";
const string fizzbuzz = "FIZZBUZZ";

// I did this solution second
for (int i = 1; i < 101; i++)
{
string output;
if (i / 15 * 15 == i) output = fizzbuzz;
else if (i / 3 * 3 == i) output = fizz;
else if (i / 5 * 5 == i) output = buzz;
else output = i.ToString();
Console.WriteLine(output);
}

// and this solution third
for (int i = 1; i < 101; i++)
{
string output = (i / 15 * 15 == i) ? fizzbuzz : (i / 3 * 3 == i)
? fizz : (i / 5 * 5 == i) ? buzz : i.ToString();
Console.WriteLine(output);
}

Console.ReadLine();
}
}
}
// Trust me, you don't want to see the one I did first.

5 comments:

  1. string prinntFB = (i % 3 == 0) ? "fizz" : ( i % 5 == 0) ? "Buzz" : ( i % 15 == 0) ? "FizzBuzz" : Convert.ToString(i);

    ReplyDelete
    Replies
    1. Ah of course, the Mod function. Thanks!

      You would still want to put the most restrictive check 1st,(i % 15 == 0), otherwise it will never be hit.

      So your code should be:

      string prinntFB = (i % 15 == 0) ? "FizzBuzz" : (i % 3 == 0) ? "fizz" : (i % 5 == 0) ? "Buzz" : Convert.ToString(i);

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. string result ='';
    for(i=1;i<101;i++)
    {
    if(i % 3==0)
    result="fizz";
    if(i%5==0)
    result=result+"buzz";
    if(result.length ==0 )
    result=i.toString();
    Console.WriteLine(result);
    }

    ReplyDelete
  4. Enumerable.Range(1, 100)
    .ToList()
    .ForEach(
    i =>
    Console.WriteLine((i%15 == 0)
    ? "FizzBuzz"
    : (i%3 == 0) ? "Fizz" : (i%5 == 0) ? "Buzz" : i.ToString()));

    ReplyDelete