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.
Tuesday, February 1, 2011
Two C# Solutions for the FizzBuzz Problem
In case you are interested...
Subscribe to:
Post Comments (Atom)
string prinntFB = (i % 3 == 0) ? "fizz" : ( i % 5 == 0) ? "Buzz" : ( i % 15 == 0) ? "FizzBuzz" : Convert.ToString(i);
ReplyDeleteAh of course, the Mod function. Thanks!
DeleteYou 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);
This comment has been removed by the author.
ReplyDeletestring result ='';
ReplyDeletefor(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);
}
Enumerable.Range(1, 100)
ReplyDelete.ToList()
.ForEach(
i =>
Console.WriteLine((i%15 == 0)
? "FizzBuzz"
: (i%3 == 0) ? "Fizz" : (i%5 == 0) ? "Buzz" : i.ToString()));